2015-05-11 7 views
7

Sto usando il codice successivo per aggiungere un'immagine a un'UITextView:Come recuperare la foto da UITextView dopo averla aggiunta utilizzando NSAttributedString?

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(200,200,140,140)]; 
    textView.font = [UIFont systemFontOfSize:20.0f]; 
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Test with emoji"]; 
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init]; 
    textAttachment.image = [UIImage imageNamed:@"Angel.png"]; 

    //for the padding inside the textView 
    textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:3.0 orientation:UIImageOrientationUp]; 
    NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment]; 
    [attributedString replaceCharactersInRange:NSMakeRange(5, 1) withAttributedString:attrStringWithImage]; 
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:NSMakeRange(0, attributedString.length)]; 
    textView.attributedText = attributedString; 
    NSLog(@"Text view: %@", textView.attributedText); 

    [self.view addSubview:textView]; 

e il risultato si presenta così:

enter image description here

ciò che mi interessa in, è come posso sapere quale immagine è stata inserita nel campo di testo e nella posizione della strega? Stavo pensando di usare attributedText, come si può osservare nel codice, dal momento che registra:

Text view: Test { 
    NSFont = "<UICTFont: 0x7ff0324f2110> font-family: \".HelveticaNeueInterface-Regular\"; font-weight: normal; font-style: normal; font-size: 17.00pt"; 
}{ 
    NSAttachment = "<NSTextAttachment: 0x7ff032682bc0>"; 
    NSFont = "<UICTFont: 0x7ff0324f2110> font-family: \".HelveticaNeueInterface-Regular\"; font-weight: normal; font-style: normal; font-size: 17.00pt"; 
}with emoji{ 
    NSFont = "<UICTFont: 0x7ff0324f2110> font-family: \".HelveticaNeueInterface-Regular\"; font-weight: normal; font-style: normal; font-size: 17.00pt"; 
} 

Aggiornamento

Estratto l'immagine utilizzando il codice:

NSMutableArray *imagesArray = [[NSMutableArray alloc] init]; 
    [attributedString enumerateAttribute:NSAttachmentAttributeName 
           inRange:NSMakeRange(0, [attributedString length]) 
           options:0 
           usingBlock:^(id value, NSRange range, BOOL *stop) 
    { 
     if ([value isKindOfClass:[NSTextAttachment class]]) 
     { 
      NSTextAttachment *attachment = (NSTextAttachment *)value; 
      UIImage *image = nil; 
      if ([attachment image]) 
       image = [attachment image]; 
      else 
       image = [attachment imageForBounds:[attachment bounds] 
            textContainer:nil 
            characterIndex:range.location]; 

      if (image) 
       [imagesArray addObject:image]; 
     } 
    }]; 

Ma cosa succede se attributoString contiene più di 1 foto consecutiva? esempio:

  • se la stringa contiene due foto consecutive poi viene aggiunto solo uno alla matrice come appare

enter image description here

codice

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Test with emoji "]; 
    [attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage]; 
    [attributedString replaceCharactersInRange:NSMakeRange(5, 1) withAttributedString:attrStringWithImage]; 

registro :

Image array: (
    "<UIImage: 0x7fd4e3e56760>" 
) 
  • se le foto non sono consecutivi l'entrambi sono aggiunti correttamente alla matrice come appare

enter image description here

codice

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Test with emoji "]; 
[attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage]; 
    [attributedString replaceCharactersInRange:NSMakeRange(16, 1) withAttributedString:attrStringWithImage]; 

registro

Image array: (
    "<UIImage: 0x7f9ce35a4a70>", 
    "<UIImage: 0x7f9ce35a4a70>" 
) 

Quindi, c'è un bug in quello che sto facendo o uno con il metodo enumerateAttribute?

Update 2 riuscito a risolvere il problema se creo una nuova istanza textAttachment e attrStringWithImage per ogni foto aggiungo.

+1

Enumerate il vostro 'NSAttributedString'. Qui, ho appena mantenuto l'immagine, ma potete anche salvare l'intervallo che è indicato nel blocco: http://stackoverflow.com/questions/29152660/extract -uiimage-from-nsattributed-string/29153172 # 29153172 – Larme

+0

@Larme puoi formulare una risposta e includere anche la risposta alla mia seconda domanda su come ottenere tutte le immagini se ce ne sono più di una? Grazie in anticipo! –

risposta

3

Il recupero delle immagini è spiegato here.

Il tuo nuovo problema è che se due immagini sono consecutive e uguali.

Così, invece di:

if (image) 
    [imagesArray addObject:image]; 

È necessario ad altri controlli, questo farà per due immagini, ma non si può sapere se sono consecutivi o non consecutivi.

if (image) 
{ 
    if ([imagesArray lastObject] != image) 
     [imagesArray addObject:image]; 
} 

quindi è necessario mantenere i riferimenti del NSRange troppo.

if (image) 
{ 
    if ([imagesArray count] > 0) 
    { 
     NSDictionary *lastFound = [imagesArray lastObject]; 
     NSRange lastRange = [lastFound[@"range"] rangeValue]; 
     UIImage *lastImage = lastFound[@"image"]; 
     if (lastImage == image && lastRange.location+lastRange.length == range.location) 
     { //Two images same & consecutive} 
     else 
     { 
      [imagesArray addObject:@{@"image":image, @"range":[NSValue valueWithRange:range]}]; 
     } 
    } 
    else 
    { 
     [imagesArray addObject:@{@"image":image, @"range":[NSValue valueWithRange:range]}]; 
    } 
} 

Recupero solo immagini:

NSArray *onlyImages = [imagesArray valueForKey:@"image"]; 

Nota: Non ho controllato se questo codice di compilazione, ma si dovrebbe ottenere l'idea. Il calcolo del mio intervallo potrebbe essere errato (manca un po 'di +1/-1, ma non è difficile verificarlo con il test) e cosa succede se c'è spazio tra due stesse immagini consecutive? Si consiglia di ottenere la stringa tra (NSString *stringBetween = [[attributedString string] substringWithRange:NSMakeRange(lastRange.location+lastRange.length, range.location-lastRange.location+lastRange.length)], e verificare la presenza di spazi, caratteri Ponctuation (ci sono un sacco di modo di farlo)

Nota aggiuntiva:. Nel tuo caso, solo il confronto image != newImage può essere sufficiente, ma se usi le immagini web, o anche due immagini con un nome diverso nel tuo pacchetto ma identiche, è un altro problema sapere se sono uguali. Ci sono alcune domande su SO sul confronto di due immagini, ma ciò dovrebbe richiedere del tempo/risorse

+0

Ho un'altra domanda: D Come posso distinguere la posizione di un'immagine in NSMutableAttributedString? Ti sto chiedendo perché un utente può apportare alcune modifiche al testo e così via, quindi c'è un modo, un metodo per recuperare facilmente la posizione di un'immagine in un NSMutableAttributoStringa? –

+1

Cosa intendi per posizione? Questa potrebbe essere un'altra domanda/argomento forse. – Larme

+0

per esempio nel mio esempio iniziale inserisco la mia immagine all'indice 5, quindi la mia domanda è: come posso recuperare la posizione/l'indice in cui è l'immagine? ovviamente se l'utente apporta alcune modifiche alla stringa, l'indice non sarà più all'indice 5 –