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

How to use info button on a UIBarButtonItem?

如何使用 UIBarButtonItem 上的信息灯?

我不想使用自定义图像,因为结果不是很好。

我想在使用 Swift 的 UIBarButtonItem 上使用 Apple“信息”按钮。

没有直接的方法可以使用 UIBarButtonItem APIs 创建这样的栏按钮。

虽然您可以使用配置有 .InfoLight UIButton 的自定义视图,但建议 here:

// 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

如果您需要更多帮助,请随时发表评论。

我会像这样使其易于重复使用:

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(_:)))

正在改编 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;

Swift4,iOS12,Xcode10

另一种方法:

  1. 将对象菜单中的栏按钮项拖到导航栏中。

  2. 控制从 barButtonItem 拖动到视图控制器以创建插座。

  3. 在 viewDidLoad 中你可以指定 UIButton.customView 如下。

    let infoButton = UIButton(type: .infoLight)
    
    infoButton.addTarget(self, action: #selector(infoAction), for: .touchUpInside)
    
    infoBarButtonOutlet.customView = infoButton 
    
    //where infoBarButtonOutlet is the outlet you created in step 2.
    
    // Be sure to add @objc before func when you create your function.
    // for example: 
    @objc func infoAction () {
    
    }
    

您可以在 Interface Builder 中按如下方式执行此操作:

  1. 将一个 UIButton 对象拖到工具栏上

  2. 设置按钮类型为"Info Light"