如何在 `swift` 中设置 `UISegmentControl` 的 borderColor?

How to set borderColor of `UISegmentControl` in `swift`?

问这个问题之前,我搜索了一下Whosebug,找到了一个相关的post:

change segmentControl border color

但我们可以看到它是 objective-c 语言。

那么我们如何改变 UISegmentControlswift 中的 borderColor 呢?

您只需将代码转换为 swift...

let customSegmentedControl = UISegmentedControl.appearance()    
customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)

但我相信您发布的代码改变了字母的实际颜色,而不是外面的颜色。外面的颜色叫"tint",改成这样:

customSegmentedControl.tintColor = UIColor.blue

编辑:仅更改边框

由于 SegmentedControl 中的每个段都是一个实际的 UIView,您可以直接访问它们并根据您的需要自定义它们,如 this answer

或者你可以设置"background image",我相信可以设置成你需要的颜色。 (虽然上面的方法看起来没那么复杂)

我们可以通过设置背景图片来达到效果。

    let customSegmentedControl = UISegmentedControl.appearance()
    //customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)

    customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni2.png"), for: .normal, barMetrics: .default)
    customSegmentedControl.setBackgroundImage(UIImage.init(named: "ni.png"), for: .selected, barMetrics: .default)

更简单的方法:

segmentControl.layer.borderWidth = 1.0
segmentControl.layer.cornerRadius = 5.0
segmentControl.layer.borderColor = UIColor.red.cgColor
segmentControl.layer.masksToBounds = true
self.segementControl.layer.borderWidth = 0.3
self.segementControl.layer.cornerRadius = 3.0
self.segementControl.layer.borderColor = UIColor.orange.cgColor

添加出口

@IBOutlet weak var customSegment: UISegmentedControl!

然后在你的 viewDidload 方法中

    customSegment.layer.borderWidth = 1.0
    customSegment.layer.cornerRadius = 5.0
    customSegment.layer.borderColor = UIColor.red.cgColor
    customSegment.layer.masksToBounds = true