实例化UISegementedControl的子类时,对类使用未实现的初始化程序'init(frame:)'

问题描述 投票:0回答:1

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

知道我想念什么吗?

致命错误:对类'TestingSubclassing.MySegmentControl'使用未实现的初始化程序'init(frame:)'

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")
    }
}
ios swift uisegmentedcontrol
1个回答
1
投票

您可以呼叫super.init(frame并插入句段手动

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")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.