Fast unrecognized selector sent to instance segment control
I am trying to add a selector to my 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)
Then:
func changeColor(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 1:
segmentedControl.backgroundColor = UIColor.green
case 2:
segmentedControl.backgroundColor = UIColor.blue
default:
segmentedControl.backgroundColor = UIColor.purple
}
}
However, when I click it I got the error - unrecognized selector sent to instance 0x7fcf5f049000
source to share
Krunal's answer is correct and will fix your mistake, but to understand why this was done you can read this :
Using string literals for selector names is extremely buggy: there is no check that a string is a well-formed selector, especially since it refers to any known method or method of the intended class. Also, for the purpose of performing automatic renaming of the Objective-C API, the relationship between the Swift name and the Objective-C selector is not obvious. By providing an explicit "create selector syntax based on the Swift method name, we eliminate the need for developers to reason about the actual Objective-C selectors used."
Although, if you want to use the Selector syntax, and there may be times when you want to call a method with dynamic string names, you can still use the Selector syntax. For methods in classes that subclass NSObject, you can directly use Selector with a string literal to call the methods. The only condition is that you need to pass the syntax of the Objective-C method inside the Selector.
In your case, this will work:
segmentedControl.addTarget(self, action: Selector(("changeColorWithSender:")), for:.valueChanged)
source to share