Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/99.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 错误:点击UISegmentedControl时将无法识别的选择器发送到实例_Ios_Swift_Uisegmentedcontrol - Fatal编程技术网

Ios 错误:点击UISegmentedControl时将无法识别的选择器发送到实例

Ios 错误:点击UISegmentedControl时将无法识别的选择器发送到实例,ios,swift,uisegmentedcontrol,Ios,Swift,Uisegmentedcontrol,我在点击其中一个片段以触发操作时出错 知道我做错了什么吗 错误: 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[TestingSubclass.MySegmentControl segmentActionWithSender:]:未识别的选择器发送到实例0x7f9217907750' ViewController中的用法 我还尝试过如下更改选择器 让segment1=MySegmentControlactionName:selectorseg

我在点击其中一个片段以触发操作时出错

知道我做错了什么吗

错误:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[TestingSubclass.MySegmentControl segmentActionWithSender:]:未识别的选择器发送到实例0x7f9217907750'

ViewController中的用法 我还尝试过如下更改选择器

让segment1=MySegmentControlactionName:selectorsegmentActionsender: 和 让segment1=MySegmentControlactionName:segmentAction

你一定是个新手! 您应该删除self.addTargetself,action:self.actionName,对于:。值在类MySegmentControl中更改,添加以下函数viewDidLoad:

segmentOne.addTargetself,操作:selectorsegmentActionsender:,for:.valueChanged
问题是您已将操作目标设置为self,这意味着将在段控制器而不是视图控制器上调用选择器。您可能会更好地使用委派模式或提供回调Closure我同意此解决方案,但是,仅供参考-我最初尝试将选择器作为参数传递,以最小化ViewController中的代码量,并可能使用一行代码创建UISegmentedControl,例如,让segment1=MySegmentControlactionName:selectorsegmentAction。非常感谢。@fs_tigre看到我对你上一个问题的编辑过的答案。@vadian-这正是我想要的。这是我问题的确切答案。
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")
    }
}
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")
    }
}