【问题标题】:How to add an action to a UIBarButton programmatically?如何以编程方式向 UIBarButton 添加操作?
【发布时间】:2021-11-13 16:39:48
【问题描述】:

我一直在使用 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")
    }
}

【问题讨论】:

  • 您能展示一下您现在是如何创建UIBarButtonItem 的吗?
  • 我刚刚更新了我的问题。
  • 我很惊讶它实际上可以编译!我知道你的困惑来自哪里。

标签: ios swift uibarbuttonitem


【解决方案1】:

你可以将一个目标-动作对传递给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
}

请参阅文档here

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

【讨论】:

  • 我的代码不起作用。请查看我的代码并告诉我哪里做错了。
  • @asnerdyasSteveWozniak “不起作用”是什么意思?
  • print 没有出现。
  • @asnerdyasSteveWozniak 我无法复制。请出示minimal reproducible example
  • 基本视图控制器完成;我只是复制了整个代码并将其粘贴到问题中。
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 2011-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多