UIButton addTarget 没有被调用

UIButton addTarget doesn't get called

我正在尝试创建一个内部有 UITextFieldUIAlertController
文本字段的右侧应该有一个按钮(使用 rightView 属性)。该按钮应显示图像而不是常规文本按钮。

当我单击文本字段的按钮时,函数 btnClicked 应该被调用,但实际上从未被调用过。

let alert = UIAlertController(title: "Testing", message: "", preferredStyle: .alert)
            
alert.addTextField { (field) in
    let chk = UIButton(type: UIButtonType.custom)
    chk.frame = CGRect(x: 2, y: 2, width: 18, height: 18)
    chk.tag = i
    chk.isUserInteractionEnabled = true
    chk.addTarget(self, action: #selector(self.btnClicked(sender:)), for: .touchUpInside)
    // I also tried the following:
    // chk.addTarget(chk, action: #selector(self.btnClicked(sender:)), for: .touchUpInside)

                    
    chk.setImage(UIImage(named: "rectangle"), for: .normal)
    chk.setImage(UIImage(named: "rectangle"), for: .selected)
    chk.setImage(UIImage(named: "rectangle"), for: .highlighted)
    chk.imageView!.contentMode = UIViewContentMode.scaleAspectFit
    chk.adjustsImageWhenHighlighted = true
                    
    field.rightView = chk
    field.rightViewMode = .always
}
            
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
            
self.present(alert, animated: true, completion: nil)

这是btnClicked函数:

@objc func btnClicked(sender: UIButton) {
    print("test")
}

目前,我只是尝试打印 test,看看它是否有效,但没有任何内容打印到控制台。
难道我做错了什么?到目前为止,我无法在单击 chk 按钮后调用 btnClicked 函数。

将目标 chk 更改为 self(或您的 btnClicked 函数所在的位置)

chk.addTarget(self, action: #selector(self.btnClicked(sender:)), for: .touchUpInside)

我有 运行 你的代码,有一些编译错误,我已经修复了。它工作得很好。每当我点击按钮时,它每次都会在控制台中打印“测试”。

 func showAlert(){
   let alert = UIAlertController(title: "Testing", message: "", preferredStyle: .alert)

    alert.addTextField { (field) in
        let chk = UIButton(type: UIButton.ButtonType.custom)
        chk.frame = CGRect(x: 2, y: 2, width: 18, height: 18)
        chk.tag = 1
        chk.isUserInteractionEnabled = true
        chk.addTarget(self, action: #selector(self.btnClicked(sender:)), for: .touchUpInside)
        // I also tried the following:
        // chk.addTarget(chk, action: #selector(self.btnClicked(sender:)), for: .touchUpInside)


        chk.setImage(UIImage(named: "rectangle"), for: .normal)
        chk.setImage(UIImage(named: "rectangle"), for: .selected)
        chk.setImage(UIImage(named: "rectangle"), for: .highlighted)
        chk.imageView!.contentMode = UIView.ContentMode.scaleAspectFit
        chk.adjustsImageWhenHighlighted = true

        field.rightView = chk
        field.rightViewMode = .always
    }

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(alert, animated: true, completion: nil)
}

@objc func btnClicked(sender: UIButton) {
    print("test")
}