簡體   English   中英

實例化 UISegementedControl 的子類時,將未實現的初始化程序“init(frame:)”用於類

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

當我嘗試在下面的代碼中使用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")
    }
}

視圖控制器

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手動插入段。

並且您必須將target參數添加到自定義init(actionName方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM