为栏按钮项目设置图像和标题? [英] Set image and title for bar button item?

查看:18
本文介绍了为栏按钮项目设置图像和标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个自定义导航控制器,其中包含简单的文本按钮的条形按钮项.是否可以保留栏按钮项目的标题,但也可以将它们设置为图像(图标图像+标题下方).

I currently have a custom navigation controller with bar button items that are simply text buttons. Is it possible to keep the title of the bar button items but also set them as images (icon image + title underneath).

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:")
        }

推荐答案

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

You can create UIButton instance, set an image and a title for it, and then create your UIBarButtonItem with it:

    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 在哪里

where self.someAction is

func someAction() {

}

这篇关于为栏按钮项目设置图像和标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆