Swift UIButton 显示和淡入淡出子视图:在“OKButtonPressed] 上崩溃:发送了无法识别的选择器”

问题描述

我在情节提要上制作了一个 UIButton,将其连接到 ViewController。我想以编程方式使其在点击时显示“hintView”,然后通过点击“hintView”上的“OKButton”淡化“hintView”。但是当按下“OKButton”时它会崩溃:线程 1:“-[buttonToShowImgView.ViewController OKButtonPressed]:无法识别的选择器发送到实例 0x7f93d6806940”。这里有什么问题?

    var hintView: UIImageView?

    @IBAction func buttonTapped(_ sender: Any) {
        showHint()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
 
    func showHint() {
        self.hintView = UIImageView(image: UIImage(named: "hintContent"))
        hintView!.frame = view.frame
        hintView!.isUserInteractionEnabled = true
        hintView!.alpha = 1.0
        view.addSubview(hintView!)
        addOKButton()
    }

    func addOKButton() {
        let OKButton = UIButton(type: .system)
        OKButton.setTitle("OK!",for: UIControl.State.normal)
        OKButton.setTitleColor(UIColor.red,for: .normal)
        OKButton.titleLabel!.font = UIFont(name: "Avenir",size: 88)
        OKButton.backgroundColor = UIColor.clear
        OKButton.frame = CGRect(x: 0,y: hintView!.bounds.height*3/4,width: hintView!.bounds.width,height: hintView!.bounds.height/6)
        OKButton.addTarget(self,action: Selector(("OKButtonPressed")),for: UIControl.Event.touchUpInside)
        hintView!.addSubview(OKButton)
    }
    
    func OKButtonPressed() {
            self.hintView!.alpha = 0.0
    }

}

解决方法

使用 #selector() 而不是 Selector() 将选择器传递给函数。 #selector() 形式让编译器检查该方法的定义是否正确。

在这种特殊情况下,我认为问题在于您的函数缺少 @objc 标记,这是使函数具有作为选择器工作所需的动态分派所必需的。

请注意,您还应该命名以小写名称开头的函数。类型和类名应以大写字母开头,函数和变量名应以小写字母开头。这是 Swift 中的一个强约定。

,
func addOKButton() {
    let OKButton = UIButton(type: .system)
    OKButton.setTitle("OK!",for: UIControl.State.normal)
    OKButton.setTitleColor(UIColor.red,for: .normal)
    OKButton.titleLabel!.font = UIFont(name: "Avenir",size: 88)
    OKButton.backgroundColor = UIColor.clear
    OKButton.frame = CGRect(x: 0,y: hintView!.bounds.height*3/4,width: hintView!.bounds.width,height: hintView!.bounds.height/6)
    OKButton.addTarget(self,action: #selector(pressedOK()),for: .touchUpInside)
    hintView!.addSubview(OKButton)
}

@objc func pressedOK() {
    self.hintView!.alpha = 0.0
}
,
func addOKButton() {
    let OKButton = UIButton(type: .system)
    OKButton.setTitle("OK!",action: #selector(OKButtonPressed(_:)),for: .touchUpInside)
    hintView!.addSubview(OKButton)
}
  
@objc func OKButtonPressed(_ sender:UIButton) {
            self.hintView!.alpha = 0.0
    }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...