swift – 将NSAttributedString添加到UIBarButtonItem

swift – 将NSAttributedString添加到UIBarButtonItem,第1张

概述我正在尝试在后栏按钮项目上设置属性字符串. 这是我第一次尝试归因于字符串. 这是代码: self.navigationItem.hidesBackButton = true let barButtonBackStr = "< Back" var attributedBarButtonBackStr = NSMutableAttributedString(string: barBut 我正在尝试在后栏按钮项目上设置属性字符串.
这是我第一次尝试归因于字符串.
这是代码:

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中出现以下错误.

Cannot invoke initializer for type ‘UIbarbuttonItem’ with an argument
List of type ‘(Title: NSMutableAttributedString,style:
UIbarbuttonItemStyle,target: CombatOutcomeVIEwController,action:
String)’

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

解决方法 您无法直接将属性字符串设置为UIbarbuttonItem.您必须为其标题设置一个普通字符串,然后设置标题的属性:

let barbuttonBackStr = "< Back"let attributes: [String: AnyObject] = [NSFontAttributename: UIFont(name: "AmericanTypewriter-Bold",size: 18)!]let newBackbutton = UIbarbuttonItem(Title: barbuttonBackStr,action: "barbuttonBack:")newBackbutton.setTitleTextAttributes(attributes,forState: .normal)navigationItem.leftbarbuttonItem = newBackbutton

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

要为必须创建UILabel的属性定义范围,请将属性字符串设置为其attributionText属性,然后使用自定义视图创建UIbarbuttonItem:

let barbuttonBackStr = "< Back"let attributedbarbuttonBackStr = NSMutableAttributedString(string: barbuttonBackStr as String)attributedbarbuttonBackStr.addAttribute(NSFontAttributename,value: UIFont(        name: "AmericanTypewriter-Bold",range: NSRange(        location:0,length:1))let label = UILabel()label.attributedText = attributedbarbuttonBackStrlabel.sizetoFit()let newBackbutton = UIbarbuttonItem(customVIEw: label)self.navigationItem.leftbarbuttonItem = newBackbutton

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

The bar button item created by this method does not call the action method of its target in response to user interactions. Instead,the bar button item expects the specifIEd custom vIEw to handle any user interactions and provIDe an appropriate response.

总结

以上是内存溢出为你收集整理的swift – 将NSAttributedString添加到UIBarButtonItem全部内容,希望文章能够帮你解决swift – 将NSAttributedString添加到UIBarButtonItem所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1012062.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存