问题
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):
回答1:
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.
Happy to help!
来源:https://stackoverflow.com/questions/61395976/add-border-to-uisegmentedcontrol