【发布时间】:2020-01-02 02:03:03
【问题描述】:
点击其中一个片段触发操作时出现错误。
知道我做错了什么吗?
错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[TestingSubclassing.MySegmentControl segmentActionWithSender:]:无法识别的选择器发送到实例 0x7f9217907750'
import UIKit
class MySegmentControl: UISegmentedControl {
var actionName:Selector
init(actionName: Selector) {
self.actionName = actionName
super.init(frame: .zero)
insertSegment(withTitle: "Two", at: 0, animated: false)
insertSegment(withTitle: "One", at: 1, 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: self.actionName, for: .valueChanged)
self.translatesAutoresizingMaskIntoConstraints = false
}
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")
}
}
我也尝试过如下更改选择器。
let segment1 = MySegmentControl(actionName: #selector(segmentAction(sender:)))
和
let segment1 = MySegmentControl(actionName: "segmentAction")
【问题讨论】:
-
问题是你已经将action target设置为
self,这意味着选择器将在段控制器上被调用,而不是在视图控制器上。您可能会更好地使用委托模式或提供回调闭包
标签: ios swift uisegmentedcontrol