【发布时间】:2021-01-22 20:38:25
【问题描述】:
在问这个问题之前,我已经搜索了stackoverflow,找到了一个相关的帖子:
change segmentControl border color
但我们可以看到它是objective-c 语言。
那么我们怎样才能改变UISegmentControl在swift中的borderColor呢?
【问题讨论】:
标签: ios swift uisegmentedcontrol
在问这个问题之前,我已经搜索了stackoverflow,找到了一个相关的帖子:
change segmentControl border color
但我们可以看到它是objective-c 语言。
那么我们怎样才能改变UISegmentControl在swift中的borderColor呢?
【问题讨论】:
标签: ios swift uisegmentedcontrol
更简单的方法:
segmentControl.layer.borderWidth = 1.0
segmentControl.layer.cornerRadius = 5.0
segmentControl.layer.borderColor = UIColor.red.cgColor
segmentControl.layer.masksToBounds = true
【讨论】:
您只需将代码转换为 swift...
let customSegmentedControl = UISegmentedControl.appearance()
customSegmentedControl.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.red], for: UIControlState.normal)
但我相信您发布的代码会改变字母的实际颜色,而不是外面的颜色。外面的颜色叫做“tint”,它的变化是这样的:
customSegmentedControl.tintColor = UIColor.blue
编辑:仅用于更改边框
由于 SegmentedControl 中的每个段都是一个实际的 UIView,因此您可以直接访问它们并根据您的需要自定义它们,如 this answer。
或者您可以设置我认为可以设置为您需要的颜色的“背景图片”。 (虽然上面的方法看起来不那么复杂)
【讨论】:
我们可以设置背景图片来实现效果。
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)
【讨论】:
self.segementControl.layer.borderWidth = 0.3
self.segementControl.layer.cornerRadius = 3.0
self.segementControl.layer.borderColor = UIColor.orange.cgColor
【讨论】: