Swift: unrecognized selector sent to instance

前端 未结 3 1835
傲寒
傲寒 2020-12-21 17:30

Why isn\'t this working:

    self.backButton?.addTarget(self, action: Selector(\"backButtonPressed:\"), forControlEvents: .TouchUpInside)

   // unrecognize         


        
3条回答
  •  被撕碎了的回忆
    2020-12-21 17:55

    If I am not wrong you have declared your backButtonPressed method inside another method like this:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let button = UIButton(frame: CGRectMake(150, 240, 75, 30))
        button.setTitle("Next", forState: UIControlState.Normal)
        button.addTarget(self, action: Selector("backButtonPressed:"), forControlEvents: UIControlEvents.TouchUpInside)
        button.backgroundColor = UIColor.greenColor()
        self.view.addSubview(button)
    
        func backButtonPressed(sender:AnyObject?) {
    
            print("Called")
        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    

    This is wrong way.

    Declare your method outside as shown in below code:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let button = UIButton(frame: CGRectMake(150, 240, 75, 30))
        button.setTitle("Next", forState: UIControlState.Normal)
        button.addTarget(self, action: Selector("backButtonPressed:"), forControlEvents: UIControlEvents.TouchUpInside)
        button.backgroundColor = UIColor.greenColor()
        self.view.addSubview(button)
    }
    
    func backButtonPressed(sender:AnyObject?) {
    
        print("Called")
    }
    

提交回复
热议问题