导航栏按钮项的图像和文本。迅速

时间:2017-02-11 22:40:56

标签: ios swift uinavigationbar

我看到了this question的答案,用于向左侧导航栏项添加图片。我成功地做到了。

但我还想在图片旁边添加一个小文字。例如,我想显示用户拥有多少硬币。所以我需要显示硬币图像和旁边的硬币数量。怎么办呢?

我尝试设置标题(使用" 123"),但我只看到图像而不是标题。这是我的代码:

let button = UIButton.init(type: .custom)
    button.setImage(UIImage.init(named: "coins.png"), for: UIControlState.normal)
    button.addTarget(self, action:#selector(self.callMethod), for: UIControlEvents.touchUpInside)
    button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
    button.setTitle("123", for: UIControlState.normal)
    let barButton = UIBarButtonItem.init(customView: button)
    self.navigationItem.leftBarButtonItem = barButton

感谢。

4 个答案:

答案 0 :(得分:4)

由于使用自定义视图初始化了条形按钮项,因此您可以将UIImageUILabel添加到一个视图,并使用UIButton来捕获触摸事件,以及将其传递给初始化程序。

    // the UIButton is simply there to capture touch up event on the entire bar button view.
    let button = UIButton.init(type: .custom)
    button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    imageView.image = UIImage(named: "coins")
    let label = UILabel(frame: CGRect(x: 35, y: 0, width: 50, height: 30))
    label.text = "1234"
    let buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 30))
    button.frame = buttonView.frame
    buttonView.addSubview(button)
    buttonView.addSubview(imageView)
    buttonView.addSubview(label)
    let barButton = UIBarButtonItem.init(customView: buttonView)
    self.navigationItem.leftBarButtonItem = barButton

当然,您可能需要相应地调整框架以供自己使用。

答案 1 :(得分:0)

使用self.navigationItem.leftBarButtonItems

数组的UIBarButtonItem
let button = UIBarButtonItem()
let text = UIBarButtonItem()

self.navigationItem.leftBarButtonItems = [button, text]

答案 2 :(得分:0)

我认为你的问题是它试图让它变大50的宽度

let buttonContainer:UIView = UIView()
buttonContainer.frame = CGRect(x: 0, y: 0, width: 50, height: 32)

let image = UIImage(named: "coins")

let button = UIButton.init(type: .system)
button.setImage(image, for: .normal)
button.frame = buttonContainer.frame
button.setTitle("sss", for: .normal)      
button.addTarget(self, action: #selector(action(_:)), for: .touchUpInside)

buttonContainer.addSubview(button)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: buttonContainer)

答案 3 :(得分:0)

您可以使用backgroundImage for image和setTitle来测试按钮。 按照这个链接肯定会有你的想法:

image for nav bar button item swift