How can I change the font of ONE segment in a UISegmentedControl?
I know how to do it for the entire control. But I want to highlight one segment if the user has something there. However this one is NOT selected.
Note: I'm using swift 3
Thanks!
How can I change the font of ONE segment in a UISegmentedControl?
I know how to do it for the entire control. But I want to highlight one segment if the user has something there. However this one is NOT selected.
Note: I'm using swift 3
Thanks!
Ok so the comments were right. I needed an image for that segment. I cobbled together some answers to get this:
DispatchQueue.main.async(execute: {
//custom funct to determine the index / just use your index
guard let segIndexL = self.navMode?.determineIndexForMode(navType: navType) else {
return
}
let width: CGFloat = 29.0
let height: CGFloat = 24.0 //height (28) minus 2pt border for top and bottom
let size = CGSize(width: width, height: height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
var fontSize: CGFloat? = nil
for segment in self.segSubViewNavControl.subviews {
for label in segment.subviews {
if label is UILabel {
fontSize = (label as! UILabel).font.pointSize + 1.0;
break
}
if fontSize != nil {
break
}
}
}
guard let fontSizeL = fontSize else {
return
}
let font = UIFont.boldSystemFont(ofSize: fontSizeL)
let txtAttributes = [
NSFontAttributeName : font,
NSForegroundColorAttributeName : UIColor.red
] as [String : Any]
guard let titleL = self.segSubViewNavControl.titleForSegment(at: segIndexL) else {
return
}
let stringSizeL = titleL.size(attributes: txtAttributes)
let rectText = CGRect(x: (width - stringSizeL.width) / 2, y: (height - stringSizeL.height) / 2, width: stringSizeL.width, height: stringSizeL.height)
titleL.draw(
in: rectText,
withAttributes: txtAttributes
)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.segSubViewNavControl.setImage(newImage, forSegmentAt: segIndexL)
})
I got these answers from here:
iOS Drawing text in the centre of shapes
How to make text appear in centre of the image?
How to Create a CGSize in Swift?
How do I add text to an image in iOS Swift
Thanks!