如何在 UIBarButtonItem
上使用信息提示灯?
我不想使用自定义图像,因为效果不太好。
我想使用 Swift 实现在 UIBarButtonItem 上使用苹果的“信息”按钮。
如何在 UIBarButtonItem
上使用信息提示灯?
我不想使用自定义图像,因为效果不太好。
我想使用 Swift 实现在 UIBarButtonItem 上使用苹果的“信息”按钮。
使用UIBarButtonItem
APIs无法直接创建这样的工具栏按钮。
不过,你可以按照这里的建议,使用一个配置了.InfoLight
UIButton
的自定义视图。
// Create the info button
let infoButton = UIButton(type: .infoLight)
// You will need to configure the target action for the button itself, not the bar button itemr
infoButton.addTarget(self, action: #selector(getInfoAction), for: .touchUpInside)
// Create a bar button item using the info button as its custom view
let infoBarButtonItem = UIBarButtonItem(customView: infoButton)
// Use it as required
navigationItem.rightBarButtonItem = infoBarButtonItem
如果需要更多帮助,请随意留下评论。
将mokagio关于Obj-C的出色答案进行改编:
UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(getInfoAction:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* infoBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
self.navigationItem.rightBarButtonItem = infoBarButtonItem;
class InfoBarButtonItem: UIBarButtonItem {
init(_ type: UIButtonType = .infoLight, target: Any, action: Selector) {
super.init()
let button = UIButton(type: type)
button.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
self.customView = button
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
然后你可以这样使用:
navigationItem.rightBarButtonItem =
InfoBarButtonItem(.infoLight, target: self, action: #selector(anAction(_:)))
将UIButton对象拖动到工具栏上
将按钮类型设置为“Info Light”
Swift 4,iOS 12,Xcode 10
另一种方法是:
从对象菜单中拖动一个“Bar Button Item”到您的导航栏。
从“barButtonItem”控制拖动到您的视图控制器以创建一个插座。
在“viewDidLoad”中,您可以指定“UIButton.customView”如下。
let infoButton = UIButton(type: .infoLight)
infoButton.addTarget(self, action: #selector(infoAction), for: .touchUpInside)
infoBarButtonOutlet.customView = infoButton
//其中infoBarButtonOutlet是您在步骤2中创建的插座。
//创建函数时,请确保在func之前添加@objc。
//例如:
@objc func infoAction () {
}