微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义文本颜色和UITabBarItem的字体导致怪异导致swift

我正在尝试更改我的UITabBarItems的文本,并使用了诸如 this之类的问题.第二个答案对我很有用,除非我尝试调整UITabBarItem的字体.此代码生成所选文本的预期结果为白色,未选中的项目为浅灰色:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()],forState:.normal)

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()],forState:.Selected)

enter image description here

但是,如果添加

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter",size: 13)!],forState: .Selected)

enter image description here

由于某种原因,当文本被选中和未被选中时,文本变为黑色,并且字体保持不变.

奇怪的是,如果我更改.在最后一个片段中选择.normal,那么所选文本将变为白色,文本将与代码中的字体匹配.

enter image description here

UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter",forState: .normal)

这几乎是完美的,但是未选择的文本现在没有变化.我不确定我做错了什么或这是一个错误,但如果有任何其他方法来完成这项任务,我很乐意听到它.

基于dfri的评论,我试过这个:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor(),NSFontAttributeName : [NSFontAttributeName:UIFont(name: "American Typewriter",size: 13)!]],forState:.Selected)

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.whiteColor(),forState:.normal)

现在应用程序崩溃了.错误说:

unrecognized selector sent to instance 0x7fa6d9461ef0

这对我没有任何意义

解决方法

请尝试以下方法

let colornormal : UIColor = UIColor.blackColor()
let colorSelected : UIColor = UIColor.whiteColor()
let titleFontAll : UIFont = UIFont(name: "American Typewriter",size: 13.0)!

let attributesnormal = [
    NSForegroundColorAttributeName : colornormal,NSFontAttributeName : titleFontAll
]

let attributesSelected = [
    NSForegroundColorAttributeName : colorSelected,NSFontAttributeName : titleFontAll
]

UITabBarItem.appearance().setTitleTextAttributes(attributesnormal,forState: .normal)
UITabBarItem.appearance().setTitleTextAttributes(attributesSelected,forState: .Selected)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐