首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在swift 3中使用addTarget方法

如何在swift 3中使用addTarget方法
EN

Stack Overflow用户
提问于 2016-09-21 21:24:15
回答 10查看 111.4K关注 0票数 63

这是我的button对象

代码语言:javascript
运行
复制
    let loginRegisterButton:UIButton = {
    let button = UIButton(type: .system)
    button.backgroundColor = UIColor(r: 50 , g: 80, b: 130)
    button.setTitle("Register", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitleColor(.white, for: .normal)
    button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside)
    return button
}()

下面是我的函数

代码语言:javascript
运行
复制
    func handleRegister(){

    FIRAuth.auth()?.createUser(withEmail: email, password: password,completion: { (user, error) in

        if error != nil
        { print("Error Occured")}

        else
        {print("Successfully Authenticated")}
    })        
}

我得到了编译错误,如果addTarget删除,它编译成功

EN

回答 10

Stack Overflow用户

发布于 2016-11-08 17:50:24

是,如果没有参数,不要添加"()“

代码语言:javascript
运行
复制
button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside). 

如果你想让发送者

代码语言:javascript
运行
复制
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside). 

func handleRegister(sender: UIButton){
   //...
}

编辑:

代码语言:javascript
运行
复制
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)

不再起作用,您需要将选择器中的_替换为您在函数头中使用的变量名,在本例中它将是sender,因此工作代码为:

代码语言:javascript
运行
复制
button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
票数 111
EN

Stack Overflow用户

发布于 2017-11-22 15:04:36

尝试使用Swift 4

代码语言:javascript
运行
复制
buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside)
@objc func actionWithParam(sender: UIButton){
    //...
}

buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside)
@objc func actionWithoutParam(){
    //...
}
票数 23
EN

Stack Overflow用户

发布于 2016-09-21 21:29:41

尝尝这个

代码语言:javascript
运行
复制
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside). 

只需添加带有方法名称的括号即可。

你也可以参考链接:Value of type 'CustomButton' has no member 'touchDown'

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39617873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档