Search code examples
iosswiftuisegmentedcontrol

Error: Unrecognised selector sent to instance when tap on UISegmentedControl


I'm getting an error when tap on one of the segments to trigger the action.

Any idea what am I doing wrong?

Error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestingSubclassing.MySegmentControl segmentActionWithSender:]: unrecognized selector sent to instance 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")
    }
}

Usage in 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")
    }
}

I have also tried changing the selector as follow.

let segment1 = MySegmentControl(actionName: #selector(segmentAction(sender:))) and let segment1 = MySegmentControl(actionName: "segmentAction")


Solution

  • You must be a newbie! You should remove self.addTarget(self, action: self.actionName, for: .valueChanged) in class MySegmentControl, add added the below the function viewDidLoad():

    segmentOne.addTarget(self, action: #selector(segmentAction(sender:)), for: .valueChanged)