代码之家  ›  专栏  ›  技术社区  ›  fs_tigre

在实例化UISegementedControl的子类时为类使用未实现的初始值设定项“init(frame:)”

  •  0
  • fs_tigre  · 技术社区  · 5 年前

    当我试图使用 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")
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   vadian    5 年前

    你可以打电话 super.init(frame 并插入段 手动

    class MySegmentControl: UISegmentedControl {
    
        init(actionName: Selector) {
            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(self, action: actionName, for: .valueChanged)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }