Swift5中UILabel点击事件无效问题求助
解决UILabel可点击功能无效的问题
你的代码存在两个关键错误,导致点击功能失效,修正方案如下:
错误1:使用了手势识别器抽象基类
你创建的是UIGestureRecognizer,这是抽象基类,无法直接处理点击动作,应使用具体的UITapGestureRecognizer。
错误2:Selector语法错误
#selector(uiLabelClicked())中的括号是多余的,正确写法应为#selector(uiLabelClicked)。
修正后的完整代码
@IBOutlet weak var coordinate: UILabel! override func viewDidLoad() { super.viewDidLoad() coordinate.adjustsFontSizeToFitWidth = true // 替换为UITapGestureRecognizer并修正selector写法 let tap = UITapGestureRecognizer(target: self, action: #selector(uiLabelClicked)) coordinate.addGestureRecognizer(tap) coordinate.isUserInteractionEnabled = true } @objc func uiLabelClicked(){ let alert = UIAlertController(title: "Coordinate", message: "I have been clicked...", preferredStyle: .alert) self.present(alert, animated: true, completion: nil) debugPrint("clicked") }
内容的提问来源于stack exchange,提问作者donaldjbrewer
相关产品推荐
相关产品推荐

