2016-08-04 4 views
0

Ich versuche, eine spezielle Schaltfläche Text basierend auf einer Zeichenfolge erstellen, die ich aus Informationen von einem Benutzer erstellen. Ich denke, ich mache das richtig, aber die IDE sagt mir, dassErstellen von speziellen UIButtons Text aus Substring in Swift

/'NSDictionary' nicht implizit in '[NSObject: AnyObject] konvertierbar'; meinst du, 'wie' zu verwenden, um explizit zu konvertieren?

Aber ich tue das hier

let attrString = NSMutableAttributedString(
    string: substring1 as String, 
    attributes: NSDictionary(
     object: font!, 
    forKey: NSFontAttributeName) as [NSObject : AnyObject]) 

Was mache ich hier falsch? Hier ist der gesamte Code dafür:

//applying the line break mode 
customerInfoButton?.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping; 
var buttonText: NSString = "Fight club \n" + 
          points + " pt. \n" + 
          "rank:" + myRank 

//getting the range to separate the button title strings 
var newlineRange: NSRange = buttonText.rangeOfString("\n") 

//getting both substrings 
var substring1: NSString = "" 
var substring2: NSString = "" 
var substring3: NSString = "" 

if(newlineRange.location != NSNotFound) { 
    substring1 = buttonText.substringToIndex(newlineRange.location) 
    substring2 = buttonText.substringFromIndex(newlineRange.location) 
    substring3 = buttonText.substringFromIndex(newlineRange.location) 
} 

//assigning diffrent fonts to both substrings 
let font:UIFont? = UIFont(name: "Arial", size: 12.0) 
let attrString = NSMutableAttributedString(
    string: substring1 as String, 
    attributes: NSDictionary(
     object: font!, 
    forKey: NSFontAttributeName) as [NSObject : AnyObject]) 

let attrString3 = NSMutableAttributedString(
    string: substring3 as String, 
    attributes: NSDictionary(
     object: font!, 
     forKey: NSFontAttributeName) as [NSObject : AnyObject]) 

let pointFont:UIFont? = UIFont(name: "Arial", size: 15.0) 
let attrString1 = NSMutableAttributedString(
    string: substring2 as String, 
    attributes: NSDictionary(
     object: pointFont!, 
     forKey: NSFontAttributeName) as [NSObject : AnyObject]) 

//appending both attributed strings 
attrString.appendAttributedString(attrString1) 

//assigning the resultant attributed strings to the button 
customerInfoButton?.setAttributedTitle(attrString, forState: UIControlState.Normal) 

Antwort

2

Sie können Ihre zurück Zeichenfolge auf diese Weise erstellen:

let attributes = [NSFontAttributeName: font!] 
let attrString = NSMutableAttributedString(string: substring1 as String, attributes: attributes) 
+0

, das funktioniert, und es ist eine verdammt viel sauberer und einfacher zu lesen dann, was ich tun. Vielen Dank, ich schätze es sehr! – MNM

Verwandte Themen