How to change font color of UISegmentedControl

前端 未结 12 1304
广开言路
广开言路 2020-12-04 16:30

I try to change font color from white to black for UISegmentedControl (for iOS 4.*)

UISegmentedControl *button = [[[UISegmentedControl alloc] in         


        
12条回答
  •  [愿得一人]
    2020-12-04 16:53

    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)
    

提交回复
热议问题