我试图在后栏按钮项目上设置属性字符串。
这是我第一次尝试归因于字符串
这是代码:
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
这导致Xcode中出现以下错误。
无法为类型&#39; UIBarButtonItem&#39;调用初始化程序。有一个参数 类型列表&#39;(标题:NSMutableAttributedString,样式: UIBarButtonItemStyle,target:CombatOutcomeViewController,action: 字符串)&#39;
任何人都知道如何做到这一点?谢谢。
答案 0 :(得分:11)
您无法直接将属性字符串设置为UIBarButtonItem
。您必须为其标题设置一个普通字符串,然后设置标题的属性:
let barButtonBackStr = "< Back"
let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont(name: "AmericanTypewriter-Bold", size: 18)!]
let newBackButton = UIBarButtonItem(title: barButtonBackStr, style: UIBarButtonItemStyle.Plain, target: self, action: "barButtonBack:")
newBackButton.setTitleTextAttributes(attributes, forState: .Normal)
navigationItem.leftBarButtonItem = newBackButton
这种方法有一点需要注意:您无法为属性设置范围。它全有或全无。
要为您必须创建UILabel
的属性定义范围,请将属性字符串设置为其attributedText
属性,然后使用自定义视图创建UIBarButtonItem
:
let barButtonBackStr = "< Back"
let attributedBarButtonBackStr = NSMutableAttributedString(string: barButtonBackStr as String)
attributedBarButtonBackStr.addAttribute(NSFontAttributeName,
value: UIFont(
name: "AmericanTypewriter-Bold",
size: 18.0)!,
range: NSRange(
location:0,
length:1))
let label = UILabel()
label.attributedText = attributedBarButtonBackStr
label.sizeToFit()
let newBackButton = UIBarButtonItem(customView: label)
self.navigationItem.leftBarButtonItem = newBackButton
当您想要使用此方法时,您必须知道必须将目标和操作设置为自定义视图,因为UIBarButtonItem
不再处理它。正如它在Apple的文档中所说:
此方法创建的条形按钮项不会调用该操作 响应用户交互的目标方法。相反, bar按钮项目需要指定的自定义视图来处理任何用户 互动并提供适当的回应。