Swift:addGestureRecognizer在课堂上不起作用

时间:2018-07-07 14:11:25

标签: swift uigesturerecognizer unrecognized-selector

我的课:

class SelectBox {
    internal static func openSelector(list:[String: String], parent:UIView){
        print("iosLog HELLO")
        parent.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClick(sender:))))
    }

    @objc func handleClick(sender: UITapGestureRecognizer) {
        print("iosLog CLICK")
    }
}

设置视图:

SelectBox.openSelector(list: AppDelegate.stateList, parent: bgPlaceInto)

启动打印HELLO后,但是单击view后出现以下错误:

  

2018-07-07 18:39:12.298322 + 0430 Ma [971:260558] [ChatService]:SMT:    2018-07-07 18:39:12.470392 + 0430   马[971:260525] [聊天服务]:RCV:2018-07-07 18:39:12.471851 + 0430   马[971:260591] [聊天服务]:RCV:   2018-07-07 18:39:14.674675 + 0430 Ma [971:260392] *** NSForwarding:   警告:“ Ma.SelectBox”类的对象0x100a9fc70未实现   methodSignatureForSelector:-遇到麻烦无法识别的选择器   + [Ma.SelectBox handleClickWithSender:] 2018-07-07 18:39:14.675210 + 0430 Ma [971:260392]无法识别的选择器+ [Ma.SelectBox   handleClickWithSender:]

我如何设置单击侦听器以按班查看?

谢谢

1 个答案:

答案 0 :(得分:2)

您的openSelector方法是静态的。静态上下文中的单词self是指周围类型的元类型的实例。在这种情况下,SelectorBox.Type

很显然,SelectorBox.Type没有handleClick方法。 SelectorBox可以。

您需要将openSelector方法设为非静态:

internal func openSelector(list:[String: String], parent:UIView){
    print("iosLog HELLO")
    parent.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClick(sender:))))
}

现在self引用了SelectorBox实例。

您可以这样称呼它:

// declare this at class level:
let box = SelectorBox()

// call the method like this
box.openSelector()

编辑:您的课程应如下所示:

class ViewControllerPage: UIViewController, UITableViewDelegate, UITableViewDataSource { 
    @IBOutlet var bgGenderInto: UIView!
    let box = SelectBox()  
    override func viewDidLoad() { 
        super.viewDidLoad() 
        box.openSelector(list: AppDelegate.genderList, parent: bgGenderInto) 
    }
}