在实例化 UISegementedControl 的子 class 时使用未实现的初始值设定项 'init(frame:)' for class

Use of unimplemented initializer 'init(frame:)' for class when instantiating a subclass of UISegementedControl

当我尝试在下面的代码中使用 MySegmentControl 的实例时出现以下错误。错误发生在应用程序启动后。

知道我错过了什么吗?

Fatal error: Use of unimplemented initializer 'init(frame:)' for class 'TestingSubclassing.MySegmentControl'

UISegementedControl 的子类

导入 UIKit

class MySegmentControl: UISegmentedControl {

    init(actionName: Selector) {
        let discountItems = ["One" , "Two"]
        super.init(items: discountItems)

        self.selectedSegmentIndex = 0

        self.layer.cornerRadius = 5.0
        self.backgroundColor = UIColor.red
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.blue.cgColor

        self.addTarget(self, action: actionName, for: .valueChanged)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

ViewController

import UIKit

class ViewController: UIViewController {

    let segmentOne: MySegmentControl = {
        let segment1 = MySegmentControl(actionName:  #selector(segmentAction))
        return segment1
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(segmentOne)
    }

    @objc func segmentAction (sender: UISegmentedControl) {
        print("segmentAction")
    }
}

您可以调用 super.init(frame 并手动插入段

并且您必须向自定义 init(actionName 方法添加一个 target 参数。

class MySegmentControl: UISegmentedControl {

    init(actionName: Selector, target: Any?) {
        super.init(frame: .zero)

        insertSegment(withTitle: "Two", at: 0, animated: false)
        insertSegment(withTitle: "One", at: 0, animated: false)
        self.selectedSegmentIndex = 0

        self.layer.cornerRadius = 5.0
        self.backgroundColor = UIColor.red
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.blue.cgColor

        self.addTarget(target, action: actionName, for: .valueChanged)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}