Use of unimplemented initializer 'init(frame:)

2020-08-03 08:03发布

问题:

I'm getting the following error when I try to use an instance of MySegmentControl in the code below. The error occurs right after the app is being launched.

Any idea what am I missing?

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

Subclass of UISegementedControl

import 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")
    }
}

回答1:

You could call super.init(frame and insert the segments manually.

And you have to add a target parameter to the custom init(actionName method.

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")
    }
}