如何在UIBarButtonItem上使用信息按钮?

15

如何在 UIBarButtonItem 上使用信息提示灯?

我不想使用自定义图像,因为效果不太好。

我想使用 Swift 实现在 UIBarButtonItem 上使用苹果的“信息”按钮。


通过代码还是通过界面构建器? - mokagio
代码,我认为通过Interface Builder不可能实现!谢谢。 - DanielZanchi
@Danny182 有一种方法是通过Interface Builder。请参阅我对类似问题的答案:https://dev59.com/1Jvga4cB1Zd3GeqP2nyL - VYT
5个回答

34

使用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

如果需要更多帮助,请随意留下评论。


5

将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;

0
我会这样轻松地使其可重复使用:
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(_:)))

1
@KevinStewart 这只是个人口味问题。 - iAmcR

0
您可以使用Interface Builder来完成以下操作:
  1. 将UIButton对象拖动到工具栏上

  2. 将按钮类型设置为“Info Light”


0

Swift 4,iOS 12,Xcode 10

另一种方法是:

  1. 从对象菜单中拖动一个“Bar Button Item”到您的导航栏。

  2. 从“barButtonItem”控制拖动到您的视图控制器以创建一个插座。

  3. 在“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 () {
    
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接