【问题标题】:How to change selected segment tintColor of UISegmentedControl in Swift如何在 Swift 中更改 UISegmentedControl 的选定段 tintColor
【发布时间】:2017-05-23 12:19:55
【问题描述】:

我想在 Swift 3 中更改 UISegmentedControl 选定段的 tintColor。 我在 Objective-c 中搜索了很多答案...
这是我的代码:

class ViewController:UIViewController{

var segment:UISegmentedControl

override func viewDidLoad() {
super.viewDidLoad()

segment.insertSegment(withTitle: "AAA", at: 0, animated: true)
segment.insertSegment(withTitle: "BBB", at: 1, animated: true)
segment.insertSegment(withTitle: "CCC", at: 2, animated: true)

segment.addTarget(self, action: #selector(changeValue), for: .valueChanged)
segment.selectedSegmentIndex = 0

view.addSubview(segment)

}
  func changeValue(sender:AnyObject) {

  //I don't know how to do that change color when segment selected
  // 

}

}

谢谢!

【问题讨论】:

标签: ios iphone swift uisegmentedcontrol


【解决方案1】:

在 ios 13 上使用下面的代码,

if #available(iOS 13.0, *) {
        segment.selectedSegmentTintColor = .red
} else {
        segment.tintColor = .red
}

【讨论】:

    【解决方案2】:

    以编程方式更改段的色调,

    segment.tintColor = UIColor.yellow

    【讨论】:

      【解决方案3】:

      如果你想设置标题的颜色,你可以这样做:

      let titleTextAttributes = [NSForegroundColorAttributeName: Color.blue]
      segmentedControl.setTitleTextAttributes(titleTextAttributes, forState: .Selected)
      

      【讨论】:

      • 它只是更改所选段标题的解决方案。
      【解决方案4】:

      在 Main.storyboard 中,选择 segmentControl 并更改属性“Tint”,如下图所示:

      如果您以编程方式创建 segmentedControl,请使用:

       segment.tintColor = UIColor.red
      

      【讨论】:

        【解决方案5】:

        在 iOS 13 中添加了一个新属性:selectedSegementTintColor。旧的 tintColor 属性在 iOS 13 中不再有效。

        您可以在iOS 13 UISegmentedControl: 3 important changes 找到更完整的更改记录

        【讨论】:

          【解决方案6】:

          将以下代码添加到您的 changeValue 函数中:

          func changeValue(sender: UISegmentedControl){
          for i in 0..<sender.subviews.count {
              if sender.subviews[i].isSelected() {
                  var tintcolor = UIColor.red // choose the color you want here
                  sender.subviews[i].tintColor = tintcolor
              }
              else {
                  sender.subviews[i].tintColor = nil
              }
          }
          }
          

          这是该问题已接受答案的快速版本:UISegmentedControl selected segment color

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-03-28
            • 2012-05-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多