当我尝试使用以下实例时,出现以下错误MySegmentControl
在下面的代码中。该错误发生在应用程序启动后。
知道我错过了什么吗?
致命错误:对类“TestingSubclassing.MySegmentControl”使用未实现的初始化程序“init(frame:)”
UISegmentedControl 的子类
导入 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
并插入段manually.
并且你必须添加一个target
参数自定义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")
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)