Swift: unrecognized selector sent to instance

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

Why isn\'t this working:

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

   // unrecognize         


        
3条回答
  •  伪装坚强ぢ
    2020-12-21 18:13

    Replace your action argument - selector like:

    self.backButton?.addTarget(self, action: #selector(self. backButtonPressed(sender:)), for:. touchUpInside)
    

    Since Swift 3, selector syntax has been changed as shown here.

    The use of string literals for selector name is error-prone: there is no checking that the string is even a well-formed selector, much less that it refers to any known method, or a method of the intended class. Moreover, with the effort to perform automatic renaming of Objective-C APIs, the link between Swift name and Objective-C selector is non-obvious. By providing explicit "create a selector" syntax based on the Swift name of a method, we eliminate the need for developers to reason about the actual Objective-C selectors being used.

提交回复
热议问题