I try to change font color from white to black for UISegmentedControl
(for iOS 4.*)
UISegmentedControl *button = [[[UISegmentedControl alloc] in
Updated for iOS 13:
extension UISegmentedControl
{
func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.white)
{
let defaultAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color
]
setTitleTextAttributes(defaultAttributes, for: .normal)
}
func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red)
{
let selectedAttributes = [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color
]
setTitleTextAttributes(selectedAttributes, for: .selected)
}
}
Updated for Swift 4 - Use this Extension (because extension is always awesome..!!)
extension UISegmentedControl {
func defaultConfiguration(font: UIFont = UIFont.systemFont(ofSize: 12), color: UIColor = UIColor.gray) {
let defaultAttributes = [
NSAttributedStringKey.font.rawValue: font,
NSAttributedStringKey.foregroundColor.rawValue: color
]
setTitleTextAttributes(defaultAttributes, for: .normal)
}
func selectedConfiguration(font: UIFont = UIFont.boldSystemFont(ofSize: 12), color: UIColor = UIColor.red) {
let selectedAttributes = [
NSAttributedStringKey.font.rawValue: font,
NSAttributedStringKey.foregroundColor.rawValue: color
]
setTitleTextAttributes(selectedAttributes, for: .selected)
}
}
and from the respective class, you can use these function,
@IBOutlet weak var segment: UISegmentedControl!
segment.defaultConfiguration()
// or provide paramater as per your requirement
segment.selectedConfiguration(color: .blue)