首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >自定义UITabBarItem的文本颜色和字体导致了快速的奇怪结果

自定义UITabBarItem的文本颜色和字体导致了快速的奇怪结果
EN

Stack Overflow用户
提问于 2015-12-30 22:21:15
回答 2查看 7.2K关注 0票数 6

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

代码语言:javascript
运行
复制
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState:.Normal)

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

但是,如果加上这一点:

代码语言:javascript
运行
复制
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!], forState: .Selected)

由于某种原因,当文本被选中和未选中,并且字体保持不变时,它就会变成黑色。

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

代码语言:javascript
运行
复制
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!], forState: .Normal)

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

根据dfri的评论,我尝试过这样做:

代码语言:javascript
运行
复制
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor(),
        NSFontAttributeName : [NSFontAttributeName:UIFont(name: "American Typewriter", size: 13)!]], forState:.Selected)

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

现在这个应用程序崩溃了。错误说:

发送给实例0x7fa6d9461ef0的未识别选择器

对我来说没有任何意义

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-30 23:15:50

尝试以下几点

代码语言:javascript
运行
复制
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)
票数 19
EN

Stack Overflow用户

发布于 2017-10-20 13:51:55

对于iOS 10和更高版本,您只需要更改.normal的字体,这将影响所选项目和未选定项的字体。

代码语言:javascript
运行
复制
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName : UIFont.myMediumFont(withSize: 10)], for: [.normal])

此外,您可以设置tintColors,而不必使用.setTitleTextAttributes,如下所示:

代码语言:javascript
运行
复制
UITabBar.appearance().unselectedItemTintColor = UIColor.white
UITabBar.appearance().tintColor = UIColor.black
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34538159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档