2015-12-04 35 views
7

Ho una stringa che non ha spazi bianchi alla fine della stringa ma quando sto convertendo in NSAttributedString e impostato su UITextView è stato visto degli spazi bianchi alla fine dello UILabel .Come tagliare (rimuovere) spazi bianchi dalla fine di una stringa NSAattributed

Per fare NSAttributedString Sto usando il seguente codice. Nel mio codice expectedLabelSize dà una grande altezza.

UILabel *tempLbl = [[UILabel alloc]init]; 
tempLbl.font = txtView.font; 
tempLbl.text = string; 

NSDictionary *dictAttributes = [NSDictionary dictionaryWithObjectsAndKeys: tempLbl.font, NSFontAttributeName, aParaStyle, NSParagraphStyleAttributeName,[UIColor darkGrayColor],NSForegroundColorAttributeName, nil]; 

CGSize expectedLabelSize = [string boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dictAttributes context: nil].size; 
+0

Aggiornare la domanda con il codice che inizializza 'stringa'. Perché la tua domanda parla di un 'UITextView'? Il tuo codice postato non fa menzione di una vista testuale. E cosa c'entra il 'UILabel' con la domanda? Non ha influenza su 'expectedLabelSize'. – rmaddy

+0

Hai provato a impostare a 0 e poi a sizeToFit? –

risposta

7

risposta Swift, ma vi darà un inizio se si traduce a Obj-C (o fare un file veloce solo con l'estensione per l'uso nel Obj-C poi)

extension NSMutableAttributedString { 

    func trimmedAttributedString(set: CharacterSet) -> NSMutableAttributedString { 

     let invertedSet = set.inverted 

     var range = (string as NSString).rangeOfCharacter(from: invertedSet) 
     let loc = range.length > 0 ? range.location : 0 

     range = (string as NSString).rangeOfCharacter(
          from: invertedSet, options: .backwards) 
     let len = (range.length > 0 ? NSMaxRange(range) : string.characters.count) - loc 

     let r = self.attributedSubstring(from: NSMakeRange(loc, len)) 
     return NSMutableAttributedString(attributedString: r) 
    } 
} 

Usage :

let noSpaceAttributedString = 
    attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines) 
+0

Grazie Dean, eccellente. Ho modificato le modifiche minori per l'ultimo Swift. Fantastico grazie – Fattie