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

Swift iOS开发:如何以编程方式为UIBarButton添加点击Action事件

Swift 编程式为UIBarButtonItem添加点击事件实现全局通知入口

问题背景

我目前使用Swift开发一款小型iOS兴趣项目,需要实现一个通知入口(点击铃铛形按钮可查看通知),且要在所有页面都显示该铃铛按钮。因此我打算创建一个基类视图控制器,让其他所有视图控制器都继承它,不过此时我遇到了问题:因为该铃铛按钮是通过代码创建的,没法通过⌃拖拽的方式生成IBAction,我不知道该怎么给这个按钮添加点击事件方法。我之前找到的解决方案都是针对UIButton的,不适用于UIBarButtonItem。

核心问题

如何以编程方式给UIBarButtonItem添加点击事件?

初始代码(未实现点击事件)

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加通知按钮
        let notificationButton = UIBarButtonItem(image: UIImage(systemName: "bell.fill"))
        notificationButton.tintColor = .black
        
        self.navigationItem.rightBarButtonItem = notificationButton
    }
}

自行调整后的代码

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加通知按钮
        let notificationButton = UIBarButtonItem(
            image: UIImage(systemName: "bell.fill"),
            style: .plain,
            target: self,
            action: #selector(notificationButtonPressed)
        )
        
        notificationButton.tintColor = .black
        
        self.navigationItem.rightBarButtonItem = notificationButton
    }
    
    @objc func notificationButtonPressed() {
        print("Hello")
    }
}

解答

你调整后的代码已经是UIBarButtonItem添加编程式点击事件的标准正确实现,核心注意点如下:

  • 使用带target和action参数的UIBarButtonItem构造器:target指定响应事件的对象,这里填self就是当前基类控制器响应;action指定触发的方法,用#selector()包裹方法名
  • 响应方法必须加@objc标记,因为selector依赖Objective-C运行时识别方法,缺少该标记会触发运行时崩溃

如果需要子类自定义点击逻辑,直接重写notificationButtonPressed方法即可,无需重复创建按钮:

// 子类示例
class HomePageViewController: BaseViewController {
    override func notificationButtonPressed() {
        // 不需要调用父类逻辑可以直接省略super调用
        let notificationListVC = NotificationListViewController()
        self.navigationController?.pushViewController(notificationListVC, animated: true)
    }
}

内容的提问来源于stack exchange,提问作者user17353495

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:36:04