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