I'm attempting to set an attributed string on my back bar button item.
This is my first attempt at attributed strings.
Here is the code:
self.navigationItem.hidesBackButton = true
let barButtonBackStr = "< Back"
var attributedBarButtonBackStr = NSMutableAttributedString(string: barButtonBackStr as String)
attributedBarButtonBackStr.addAttribute(NSFontAttributeName,
value: UIFont(
name: "AmericanTypewriter-Bold",
size: 18.0)!,
range: NSRange(
location:0,
length:1))
let newBackButton = UIBarButtonItem(title: attributedBarButtonBackStr, style: UIBarButtonItemStyle.Plain, target: self, action: "barButtonBack:")
self.navigationItem.leftBarButtonItem = newBackButton
This results in the following error in Xcode.
Cannot invoke initializer for type 'UIBarButtonItem' with an argument list of type '(title: NSMutableAttributedString, style: UIBarButtonItemStyle, target: CombatOutcomeViewController, action: String)'
Anyone have an idea on how to do this? Thanks.
You cannot directly set an attributed string to an
UIBarButtonItem
. You have to set a normal string to its title and then set the attributes for the title:This approach has one caveat: You cannot set a range for the attributes. It's all or nothing.
To define a range for the attributes you have to create a
UILabel
, set an attributed string to itsattributedText
property and then create aUIBarButtonItem
with a custom view:When you want to use this approach you have to know you have to set the target and the action to the custom view, because the
UIBarButtonItem
does not longer handle it. As it says in Apple's docs: