如何在UIBarButtonItem上使用info按钮

问题描述 投票:8回答:5

如何在UIBarButtonItem上使用信息灯?

我不想使用自定义图像,因为结果不是很好。 我想使用Apple“信息”按钮。 我正在使用Swift。 谢谢。

swift uibutton uibarbuttonitem
5个回答
21
投票

没有直接的方法来使用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

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


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

0
投票

改编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
投票

Swift 4,iOS 12,Xcode 10

另一种方法:

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 () {
        }

0
投票

您可以在Interface Builder中执行此操作,如下所示:

  1. 将UIButton对象拖到工具栏上
  2. 将按钮类型设置为“信息灯”
© www.soinside.com 2019 - 2024. All rights reserved.