@selector() in Swift?

后端 未结 23 2536
清酒与你
清酒与你 2020-11-21 15:24

I\'m trying to create an NSTimer in Swift but I\'m having some trouble.

NSTimer(timeInterval: 1, target: self, selector: test(), us         


        
23条回答
  •  温柔的废话
    2020-11-21 15:53

    When using performSelector()

    /addtarget()/NStimer.scheduledTimerWithInterval() methods your method (matching the selector) should be marked as

    @objc
    For Swift 2.0:
        {  
            //...
            self.performSelector(“performMethod”, withObject: nil , afterDelay: 0.5)
            //...
    
    
        //...
        btnHome.addTarget(self, action: “buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        //...
    
        //...
         NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector : “timerMethod”, userInfo: nil, repeats: false)
        //...
    
    }
    
    @objc private func performMethod() {
    …
    }
    @objc private func buttonPressed(sender:UIButton){
    ….
    }
    @objc private func timerMethod () {
    ….
    }
    

    For Swift 2.2, you need to write '#selector()' instead of string and selector name so the possibilities of spelling error and crash due to that will not be there anymore. Below is example

    self.performSelector(#selector(MyClass.performMethod), withObject: nil , afterDelay: 0.5)
    

提交回复
热议问题