向UISegmentedControl添加边框 [英] Add Border to UISegmentedControl
本文介绍了向UISegmentedControl添加边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为 UISegmentedControl
设置带有颜色的边框?
how can i set a border with a color to a UISegmentedControl
?
默认情况下,我正在获取此信息(不正确):
I'm getting this by default (incorrect):
我正在尝试,但是什么也没发生
I was trying this but nothing happens
UISegmentedControl.appearance().layer.borderWidth = 1.0
UISegmentedControl.appearance().layer.cornerRadius = 5.0
UISegmentedControl.appearance().layer.borderColor = UIColor.white.cgColor
UISegmentedControl.appearance().layer.masksToBounds = true
我想达到这个边界(正确):
i want to achieve this border (correct):
推荐答案
我使用此函数来更改我的SegmentedControl:
I use this function to alter my SegmentedControl:
func setSegmentedControlStyle(_ sgControl: UISegmentedControl, withColor: UIColor, normalTextColor: UIColor, withCornorRadius: CGFloat) {
let sgcTitleAttributes = [NSAttributedString.Key.font: UIFont.nunitoSansRegularFontOfSize(15.0)!,
NSAttributedString.Key.foregroundColor: normalTextColor] as [NSAttributedString.Key : Any]
let sgcSelectedStateTitleAttributes = [NSAttributedString.Key.font: UIFont.nunitoSansRegularFontOfSize(15.0)!,
NSAttributedString.Key.foregroundColor: _WHITE_COLOR] as [NSAttributedString.Key : Any]
if #available(iOS 13.0, *) {
sgControl.backgroundColor = UIColor.clear
let tintColorImage = UIImage(color: .clear, size: CGSize(width: 1, height: sgControl.frame.height))
let selectedTintColorImage = UIImage(color: withColor, size: CGSize(width: 1, height: sgControl.frame.height))
sgControl.setBackgroundImage(tintColorImage, for: .normal, barMetrics: .default)
sgControl.setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
sgControl.setBackgroundImage(selectedTintColorImage, for: .selected, barMetrics: .default)
sgControl.selectedSegmentTintColor = withColor
} else {
sgControl.tintColor = withColor
}
sgControl.layer.cornerRadius = withCornorRadius
sgControl.layer.borderWidth = 1.0
sgControl.layer.borderColor = withColor.cgColor
sgControl.layer.masksToBounds = true
sgControl.setTitleTextAttributes(sgcTitleAttributes, for: .normal)
sgControl.setTitleTextAttributes(sgcSelectedStateTitleAttributes, for: .selected)
}
extension UIImage {
convenience init(color: UIColor, size: CGSize) {
UIGraphicsBeginImageContextWithOptions(size, false, 1)
color.set()
let ctx = UIGraphicsGetCurrentContext()!
ctx.fill(CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.init(data: image.pngData()!)!
}
}
您可以根据需要进行游戏和更改.
You can play around and change a bit as per your needs.
如果您有任何疑问,请告诉我.
Let me know if you have any questions.
很乐意提供帮助!
这篇关于向UISegmentedControl添加边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文