Swift无法识别的选择器发送到实例分段控件

时间:2017-07-25 09:55:33

标签: ios swift

我尝试将选择器添加到我的UISegmentedControl。

    segmentedControl = UISegmentedControl(items: items)
    segmentedControl.layer.cornerRadius = 12.0
    segmentedControl.layer.borderColor = UIColor.purpleLight.cgColor
    segmentedControl.layer.borderWidth = 1.0
    segmentedControl.layer.masksToBounds = true
    segmentedControl.backgroundColor = .white
    self.contentView.addSubview(segmentedControl)

    segmentedControl.addTarget(self, action: Selector(("changeColor:")), for:.valueChanged)

然后:

func changeColor(sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 1:
            segmentedControl.backgroundColor = UIColor.green
        case 2:
            segmentedControl.backgroundColor = UIColor.blue
        default:
            segmentedControl.backgroundColor = UIColor.purple
        }
    }

然而,当我点击它时,我收到了一个错误 - unrecognized selector sent to instance 0x7fcf5f049000

2 个答案:

答案 0 :(得分:5)

替换你的动作参数 - 选择器。从Swift 3开始,选择器语法已经改变。

segmentedControl.addTarget(self, action: #selector(self.changeColor(sender:)), for:.valueChanged)

答案 1 :(得分:5)

Krunal的答案是正确的,可以解决您的错误,但要了解其原因,您可以阅读this

  

对选择器名称使用字符串文字是非常的   容易出错:没有检查字符串是否为a   格式良好的选择器,更不用说它指的是任何已知的方法,或者   预期类的方法。而且,努力表现   自动重命名Objective-C API,Swift名称之间的链接   而Objective-C选择器并不明显。通过提供明确的“创造   一个选择器“基于方法的Swift名称的语法,我们消除   开发人员需要推理实际的Objective-C   正在使用的选择器。

虽然,如果您想使用Selector语法,并且可能存在您希望通过动态字符串名称调用方法的情况,您仍然可以使用Selector语法。对于类中的方法,即NSObject的子类,可以直接使用Selector和字符串文字来调用方法。唯一的条件是你需要在Selector中传递Objective-C方法语法。

在您的情况下,这将有效:

segmentedControl.addTarget(self, action: Selector(("changeColorWithSender:")), for:.valueChanged)