2014-09-01 13 views
17

Próbuję dodać podkreślenie do tekstu w mojej aplikacji Swift. Jest to kod mam obecnie:Dodaj NSUnderlineStyle.PatternDash do NSAttributedString w Swift?

let text = NSMutableAttributedString(string: self.currentHome.name) 

let attrs = [NSUnderlineStyleAttributeName:NSUnderlineStyle.PatternDash] 

text.addAttributes(attrs, range: NSMakeRange(0, text.length)) 
homeLabel.attributedText = text 

Ale ten błąd na text.addAttributes line:

NSString nie jest identyczna NSObject

Jak mogę dodać atrybut zawarty w wyliczeniu NSMutableAttributedString w Swift?

Odpowiedz

43

Aktualizacja Swift 4 składnia:

Oto pełna przykładem tworzenia UILabel z podkreślony tekst:

let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30)) 

let text = NSMutableAttributedString(string: "hello, world!") 

let attrs = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.patternDash.rawValue | NSUnderlineStyle.styleSingle.rawValue] 

text.addAttributes(attrs, range: NSRange(location: 0, length: text.length)) 

homeLabel.attributedText = text 

Swift 2:

Swift pozwala przekazać Int do metody, która zajmuje się NSNumber, więc można zrobić to trochę czystsze usuwając konwersję do NSNumber:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length)) 

Uwaga: To Odpowiedź poprzednio używana toRaw() użyta w pierwotnym pytaniu, ale teraz jest niepoprawna, ponieważ toRaw() została zastąpiona przez właściwość rawValue od Xcode 6.1.

+0

Czy możesz zaktualizować swój kod za pomocą składni swift4. – Vats

+0

@Vats, zaktualizowano. Spójrz. – vacawama

3

Okazuje się, że potrzebne metody toRaw() - to działa:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(integer:(NSUnderlineStyle.StyleDouble).toRaw()), range: NSMakeRange(0, text.length)) 
7

w Xcode 6.1 SDK iOS 8.1 toRaw() został zastąpiony przez rawValue:

text.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: NSMakeRange(0, text.length)) 

i łatwiejsze:

var text : NSAttributedString = NSMutableAttributedString(string: str, attributes : [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]) 
13

Jeśli chcesz rzeczywistą linię przerywaną, należy LUB | surowe wartości zarówno PatternDash, jak i StyleSingle są wyliczane poniżej:

let dashed  = NSUnderlineStyle.PatternDash.rawValue | NSUnderlineStyle.StyleSingle.rawValue 

let attribs = [NSUnderlineStyleAttributeName : dashed, NSUnderlineColorAttributeName : UIColor.whiteColor()]; 

let attrString = NSAttributedString(string: plainText, attributes: attribs) 
Powiązane problemy