MNM MNM - 3 months ago 9
iOS Question

Creating special UIButtons text from substring in Swift

I am trying to create a special button text based off of a string that I am building from information from a user. I think I am doing this right, but the IDE is telling me that


/ 'NSDictionary' is not implicitly convertible to '[NSObject : AnyObject]'; did you mean to use 'as' to explicitly convert?


But I am doing that here

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


What am I doing wrong here? Here is the whole code for this:

//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)

Answer

You can create your attributed string in this way:

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