0

我在情节提要上制作了一个 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
    }

}
4

3 回答 3

2

使用#selector(), notSelector()将选择器传递给函数。该#selector()表单让编译器检查方法是否定义正确。

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

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

于 2021-03-19T20:23:16.947 回答
1
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
}
于 2021-03-19T20:15:29.913 回答
0
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: .touchUpInside)
    hintView!.addSubview(OKButton)
}
  
@objc func OKButtonPressed(_ sender:UIButton) {
            self.hintView!.alpha = 0.0
    }
于 2021-03-20T17:24:04.403 回答