一尘不染

设置条形按钮项目的图像和标题?

swift

我目前有一个带有条形按钮项的自定义导航控制器,这些条形按钮项只是文本按钮。是否可以保留条形按钮项目的标题,但也可以将它们设置为图像(图标图像+下方的标题)。

class NavigationController: UINavigationController
{
    var mode: NavigationMode = .Swipe {
        didSet {
            self.setButtonAttributes()
        }
    }

    private var leftBarButton: UIBarButtonItem!
    private var middleBarButton: UIBarButtonItem!
    private var rightBarButton: UIBarButtonItem!
    private var rightBarButton2: UIBarButtonItem!

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    func configureNavigationItem(navigationItem: UINavigationItem)
    {
        //Configure the bar buttons text and actions


        if (self.leftBarButton == nil) {
            self.leftBarButton = UIBarButtonItem(title: "Menu1", style: .Plain,target: self, action: "menu1Pressed:")
        }
        if (self.middleBarButton == nil) {
            self.middleBarButton = UIBarButtonItem(title: "Games", style: .Plain, target: self, action: "gamesPressed:")
        }
        if (self.rightBarButton == nil) {
            self.rightBarButton = UIBarButtonItem(title: "Menu3", style: .Plain, target: self, action: "menu3Pressed:")
        }
        if (self.rightBarButton2 == nil) {
            self.rightBarButton2 = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "settingsPressed:")
        }

        self.setButtonAttributes()

        navigationItem.leftBarButtonItems = [self.leftBarButton, self.middleBarButton, self.rightBarButton, self.rightBarButton2]

    }

更新:

  let button = UIButton(type: .System)
        button.setImage(UIImage(named: "play"), forState: .Normal)
        button.setTitle("Play", forState: .Normal)
        button.sizeToFit()

        leftBarButton = UIBarButtonItem(customView: button)

        if (self.leftBarButton == nil) {
            self.leftBarButton = UIBarButtonItem(title: "Play", style: .Plain,target: self, action: "Pressed:")
        }

阅读 183

收藏
2020-07-07

共1个答案

一尘不染

您可以创建UIButton实例,为其设置图像和标题,然后使用它创建UIBarButtonItem:

    let button = UIButton(type: .System)
    button.setImage(UIImage(named: "YourImage"), forState: .Normal)
    button.setTitle("YourTitle", forState: .Normal)
    button.sizeToFit()
    self.leftBarButton = UIBarButtonItem(customView: button)

要添加动作:

    button.addTarget(self, action: #selector(self.someAction), forControlEvents: .TouchUpInside)

self.someAction在哪里

func someAction() {

}
2020-07-07