You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:55:24