ios - 如何在 swift 3 中使用 addTarget 方法

标签 ios swift selector

这是我的按钮对象

    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
}()

这是我的函数

    func handleRegister(){

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

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

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

我收到编译错误,如果 addTarget 删除则编译成功

最佳答案

是的,如果没有参数就不要加“()”

button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside). 

如果您想获取发件人

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside). 

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

编辑:

button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)

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

button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)

关于ios - 如何在 swift 3 中使用 addTarget 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298347/

相关文章:

ios - 在 NSArray 中存储带有参数的 block

swift - 如何在 Swift 中将 [Int8] 转换为 [UInt8]

android - 如何设置Listview的交替行颜色和选中项背景颜色

iphone - UIImageView 旋转不正确?

ios - 使用自动收缩在 UILabel 中垂直居中

ios - 处理 iPad Mini 屏幕尺寸

swift - 演示正在进行时尝试在 <a> 上演示 <a>

swift - UISlider,保存状态

html - 一个 HTML 元素可以有多个唯一的 ID 属性吗?

automation - 动态内容的选择器问题