草庐IT

ios - 在 iOS 的 Swift 中将 TabBarItem 标题字体更改为粗体

coder 2023-09-06 原文

我正在尝试将所选标签栏项目的字体粗细设置为粗体。好像没有效果。知道什么是错的。 forState: .Normal 按预期工作,forState: .Selected 无效。

let tabBarItem0 = tabBar.items![0] as! UITabBarItem
var selectedImage0 : UIImage = UIImage(named:"ic_tabbar_item_one")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
var fontLight:UIFont = UIFont(name: "HelveticaNeue-UltraLight", size: 12)!
var fontBold:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 12)!

tabBarItem0.image = unselectedImage0
tabBarItem0.selectedImage = selectedImage0
tabBarItem0.title = "Overview"
tabBarItem0.setTitleTextAttributes(
    [
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSFontAttributeName: fontLight
    ], forState: .Normal)

tabBarItem0.setTitleTextAttributes(
    [
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSFontAttributeName: fontBold
    ], forState: UIControlState.Selected)

最佳答案

找到解决方案(Swift 3、XCode 8.1)

  1. 在 Storyboard 中,为您拥有的每个 UITabBarItem 提供一个唯一的标签:对于每个选项卡 -> 选择它并转到它的“属性检查器” -> 给每个标签一个 “标签”字段中的唯一数字,但您不应使用零(我使用 1 到 4)。

    这让我们为以后确定按下了哪个选项卡做好了准备。


  1. 创建一个新的 UITabBarController 的子类,然后赋值:FILE -> New File -> iOS Cocoa Touch -> 创建一个 UITabBarController 的子类。将新的 .swift 文件分配给你的 “身份检查器”下的 UITabBarController。

    我们的 UITabBarController 中需要自定义逻辑。


  1. 创建 UITabBarItem 的新子类,将相同的文件分配给所有 UITabBarItems:FILE -> New File -> iOS Cocoa Touch -> 创建 UITabBarItem 的子类并分配您的所有标签都使用相同的标签。

    我们需要在标签栏项目中共享自定义逻辑。


  1. 将此代码添加到您的 UITabBarItem 子类,它会设置初始状态(主要选项卡加粗,其余选项卡未选中),并允许以编程方式更改选项卡:

    class MyUITabBarItemSubclass: UITabBarItem {
    
        //choose initial state fonts and weights here
        let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) 
        let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
    
        //choose initial state colors here
        let normalTitleColor = UIColor.gray 
        let selectedTitleColor = UIColor.black
    
        //assigns the proper initial state logic when each tab instantiates 
        override func awakeFromNib() {
            super.awakeFromNib()
    
            //this tag # should be your primary tab's Tag* 
            if self.tag == 1 { 
                self.setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
            } else {
                self.setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
            }
    
        }
    
    }
    

我们在这里设置初始状态,以便在打开应用程序时正确设置选项卡,我们将在下一个子类中处理物理选项卡按下。


  1. 将此代码添加到您的 UITabBarController 子类,这是在您按下选项卡时分配正确状态的逻辑。

    class MyUITabBarControllerSubclass: UITabBarController {
    
        //choose normal and selected fonts here
        let normalTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)
        let selectedTitleFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightBold)
    
        //choose normal and selected colors here
        let normalTitleColor = UIColor.gray
        let selectedTitleColor = UIColor.black
    
    
        //the following is a delegate method from the UITabBar protocol that's available 
        //to UITabBarController automatically. It sends us information every
        //time a tab is pressed. Since we Tagged our tabs earlier, we'll know which one was pressed,
        //and pass that identifier into a function to set our button states for us
    
        override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
            setButtonStates(itemTag: item.tag)
        }
    
    
        //the function takes the tabBar.tag as an Int
        func setButtonStates (itemTag: Int) {
    
            //making an array of all the tabs
            let tabs = self.tabBar.items
    
            //looping through and setting the states
            var x = 0
            while x < (tabs?.count)! {
    
                if tabs?[x].tag == itemTag {
                    tabs?[x].setTitleTextAttributes([NSFontAttributeName: selectedTitleFont, NSForegroundColorAttributeName: selectedTitleColor], for: UIControlState.normal)
                } else {
                    tabs?[x].setTitleTextAttributes([NSFontAttributeName: normalTitleFont, NSForegroundColorAttributeName: normalTitleColor], for: UIControlState.normal)
                }
    
                x += 1
    
            }
    
        }
    
    }
    

看起来这很痛苦,因为出于某种原因,选项卡无法识别状态更改为“.Selected”。我们必须通过仅使用正常状态来完成所有工作 - 基本上我们自己检测状态变化。


  1. 您可以以编程方式更改选项卡,并且仍然可以通过...检测状态更改如果有人有兴趣,我会稍后更新,尽管问。

希望这对您有所帮助!

关于ios - 在 iOS 的 Swift 中将 TabBarItem 标题字体更改为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388659/

有关ios - 在 iOS 的 Swift 中将 TabBarItem 标题字体更改为粗体的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby-on-rails - 使用 Rmagick 或 ImageMagick 在背景上放置标题 - 2

    我有一张背景图片,我想在其中添加一个文本框。我想弄清楚如何将标题放置在其顶部的正确位置。(我使用标题是因为我需要自动换行功能)。现在,我只能让文本显示在左上角,但我需要能够手动定位它的开始位置。require'RMagick'require'Pry'includeMagicktext="Loremipsumdolorsitamet"img=ImageList.new('template001.jpg')img 最佳答案 这是使用convert的ImageMagick命令行的答案。如果你想在Rmagick中使用这个方法,你必须自己移植

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby - 在 Ruby 中将整数格式化为固定长度的字符串 - 2

    有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的

  7. ruby - 无法在 Ruby 中将 ffmpeg 作为子进程运行 - 2

    我正在尝试使用以下代码通过将ffmpeg实用程序作为子进程运行并获取其输出并解析它来确定视频分辨率:IO.popen'ffmpeg-i'+path_to_filedo|ffmpegIO|#myparsegoeshereend...但是ffmpeg输出仍然连接到标准输出并且ffmepgIO.readlines是空的。ffmpeg实用程序是否需要一些特殊处理?或者还有其他方法可以获得ffmpeg输出吗?我在WinXP和FedoraLinux下测试了这段代码-结果是一样的。 最佳答案 要跟进mouviciel的评论,您需要使用类似pope

  8. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  9. ruby - 如何跳过 CSV 文件的第一行并将第二行作为标题 - 2

    有没有办法跳过CSV文件的第一行,让第二行作为标题?我有一个CSV文件,第一行是日期,第二行是标题,所以我需要能够在遍历它时跳过第一行。我尝试使用slice但它会将CSV转换为数组,我真的很想将其读取为CSV,以便我可以利用header。 最佳答案 根据您的数据,您可以使用另一种方法和skip_lines-option此示例跳过所有以#开头的行require'csv'CSV.parse(DATA.read,:col_sep=>';',:headers=>true,:skip_lines=>/^#/#Markcomments!)do|

  10. ruby - 如何在 Ruby 中将负整数转换为二进制 - 2

    问题1:我无法通过以下方式找到将负整数转换为二进制的方法。我应该像这样转换它。-3=>"11111111111111111111111111111101"我在下面试过:sprintf('%b',-3)=>"..101"#..appearsanddoesnotshow111111bit.-3.to_s(2)=>"-11"#Thisjustadds-tothebinaryofthepositiveinteger3.问题2:有趣的是,如果我使用在线转换器,它告诉我-3的二进制是“0010110100110011”。"11111111111111111111111111111101"和"001

随机推荐