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

Eya*_*uda 0 uinavigationbar ios swift

我看到了这个问题的答案,用于将图像添加到左侧导航栏项目。我成功地做到了。

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

我试图设置标题(用“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
Run Code Online (Sandbox Code Playgroud)

谢谢。

Sam*_*tha 5

由于条形按钮项是使用自定义视图初始化的,因此您可以将 aUIImage和 a添加UILabel到一个视图中,并使用 aUIButton来捕获触摸事件,并将其传递给初始化程序。

    // 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
Run Code Online (Sandbox Code Playgroud)

当然,您可能需要根据自己的用途相应地调整框架。