将NSAttributedString添加到UIBarButtonItem

Jui*_*uio 4 uibarbuttonitem nsmutableattributedstring swift

我正在尝试在后栏按钮项目上设置属性字符串.
这是我第一次尝试归因于字符串.
这是代码:

    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
Run Code Online (Sandbox Code Playgroud)

这导致Xcode中出现以下错误.

无法使用类型为'(title:NSMutableAttributedString,style:UIBarButtonItemStyle,target:CombatOutcomeViewController,action:String)的参数列表调用类型'UIBarButtonItem'的初始值设定项'

任何人都知道如何做到这一点?谢谢.

joe*_*ern 12

您无法直接将属性字符串设置为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
Run Code Online (Sandbox Code Playgroud)

这种方法有一点需要注意:您无法为属性设置范围.这是全有或全无.

要为必须创建的属性定义范围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
Run Code Online (Sandbox Code Playgroud)

当您想要使用此方法时,您必须知道必须将目标和操作设置为自定义视图,因为UIBarButtonItem它不再处理它.正如它在Apple的文档中所说:

此方法创建的条形按钮项不会响应用户交互调用其目标的操作方法.相反,bar按钮项期望指定的自定义视图处理任何用户交互并提供适当的响应.