【问题标题】:Swift how to set default text color for UISegmentedControl?Swift 如何为 UISegmentedControl 设置默认文本颜色?
【发布时间】:2017-07-28 19:25:02
【问题描述】:

我想为 UISegmentedControl 的文本和背景设置颜色。所以我要设置四种颜色,文本和背景的默认颜色和选定颜色。

我可以使用tintColorbackgroundColor 来设置背景。但是如何设置默认的文本颜色,而不是色调颜色呢?

注意:这里是 swift3 不是旧语言。我是ios初学者,刚从swift3开始,没有前一种语言的经验。

任何帮助将不胜感激。

【问题讨论】:

    标签: ios swift iphone xcode uisegmentedcontrol


    【解决方案1】:

    这是可行的:

    // default background color
    customSC.backgroundColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
    
    // selected background color
    customSC.tintColor = UIColor(red:65/255.0, green:140/255.0, blue:218/255.0, alpha: 1.0)
    
    // selected title text color
    customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: UIControlState.selected)
    
    // default title text color
    customSC.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGray], for: UIControlState.normal)
    

    【讨论】:

      【解决方案2】:

      Swift 5+ 代码为您的UISegmentedControl(在本例中为sc)更新文本颜色

      // selected option color
      sc.setTitleTextAttributes([.foregroundColor: UIColor.green], for: .selected)
      
      // color of other options
      sc.setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
      

      【讨论】:

        【解决方案3】:

        Swift 4.2 +

        segmentedControl.tintColor = .black //background
        segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
        segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .normal)
        

        【讨论】:

          【解决方案4】:
          customSC.backgroundColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
          customSC.tintColor= UIColor(red: 0.5, greep: 0.5, blue: 0.5, alpha: 1.0)
          

          【讨论】:

          • 我要设置默认文字颜色。
          • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
          • 我找到了,检查我的答案。
          【解决方案5】:
          UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.redColor()], forState: .Selected)
          

          【讨论】:

          • 我要设置默认文字颜色。
          • 我找到了,检查我的答案。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-11-13
          • 1970-01-01
          • 1970-01-01
          • 2021-05-24
          • 2013-10-26
          • 1970-01-01
          • 2010-11-04
          相关资源
          最近更新 更多