ios - 如何以编程方式向 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")
}
}
解决方案
您可以将目标-动作对传递给 的初始化器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:_)
推荐阅读
- windows - PowerShell 脚本不保留源文件的编码
- django - 如何在 django 中的模式之间链接用户模型和用户配置文件?
- python-camelot - table_regions 和 table_areas 的区别
- ruby-on-rails - 在开发模式下使用自路由时在重定向时发送 404 状态码的任何方式
- delphi - Hook 不适用于第三个应用程序
- websphere - IBM BPM 保存更改和这些更改的可用性之间的异常时间间隔
- c++ - Win10无法从IDirectDraw7查询IDirect3D7
- javascript - 更改页面上的特定链接
- protocol-buffers - Protobuf (C++) 为可选字段抛出“缺少必需参数”错误
- python - 如何在有组织的集合中调用变量,以便在其他地方使用它?(Python)