UISegmentedControl 通过代码自定义

UISegmentedControl customize by code

我的 UISegmentedControl 有问题。我创建了 class 段:

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

    }
}

当我尝试更改某些内容时,它没有更改。在我的主要 ViewController 中,我标记了我的 UISegmentedControl 的 class 文件。

这是 ViewController 中的函数定义:

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

你能帮帮我吗?非常感谢!

来自 Apple 文档:

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

试试这个:

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
}