Search code examples
swiftclasssubclassuisegmentedcontrol

UISegmentedControl customize by code


I have problem with my UISegmentedControl. I created class of segment:

import UIKit

class CustomSegmentedControl: UISegmentedControl {

    func AwakeFromNib() {
    super.awakeFromNib()

    let myColor : UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
    self.layer.masksToBounds = true
    self.layer.borderColor = myColor.cgColor
    self.layer.borderWidth = 0.5
    self.layer.cornerRadius = 8

    }
}

When i trying change something its without changes. In my main ViewController i marked class file of my UISegmentedControl.

Here is func definition in ViewController:

 @IBAction func ShowInterval(_ sender: UISegmentedControl) {
 }

Can you help me please? Thanks you so much!


Solution

  • From Apple doc:

    The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized

    Try this:

    func layoutSubviews() {
        super.layoutSubviews()
        let myColor : UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
        self.layer.masksToBounds = true
        self.layer.borderColor = myColor.cgColor
        self.layer.borderWidth = 0.5
        self.layer.cornerRadius = 8
    }