首页 > 解决方案 > 如何以编程方式向 UIBarButton 添加操作?

问题描述

我一直在使用 Swift 创建一个小型 iOS 应用程序,只是为了好玩,我已经决定我想要一个通知框(一个钟形按钮,你可以单击以检查是否有任何通知),我还想添加每个屏幕的钟形按钮。
因此,我决定制作一个基本视图控制器并让其他视图控制器继承它。但是,那是我的问题出现的时候;我不知道如何为那个按钮添加一个动作函数。由于我以编程方式创建了钟形按钮,因此我不能只^ drag创建一个新的 IBaction。

我找到了这篇文章:link,但这是针对 UIButton 的,而不是针对 UIBarButton 的,它对我不起作用。

对不起这个长长的问题。下面是一个简单的单句问题:
我的问题
如何以编程方式向 UIBarButton 添加操作?

更新 这是我的基本视图控制器:

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add a notification button
        let notificationButton = UIBarButtonItem(image: UIImage(systemName: "bell.fill"))
        notificationButton.tintColor = .black
        
        self.navigationItem.rightBarButtonItem = notificationButton
    }
    
    
    
}

更新2

这是我的新代码:

import UIKit

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // add a notification button
        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")
    }
}

标签: iosswiftuibarbuttonitem

解决方案


您可以将目标-动作对传递给 的初始化器UIBarButtonItem

let barButton = UIBarButtonItem(
    image: UIImage(systemName: "bell.fill"), 
    style: .plain, 
    target: self, action: #selector(buttonTapped)
)

// somewhere in your view controller:

@objc func buttonTapped() {
    // do something when the bar button is tapped
}

请参阅此处的文档。

如果你熟悉的话,这类似于UIButton's方法。addTarget(_:action:for:_)


推荐阅读