【发布时间】: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