导航栏按钮项的图像和文本..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

谢谢。

由于栏按钮项是使用自定义视图初始化的,因此可以向一个视图添加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

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

我认为你的问题是宽度是 30 尝试让它像 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)

您可以将 backgroundImage 用于图像,并将 setTitle 用于测试按钮。点击此链接,您肯定会得到想法:

导航栏按钮项 SWIFT 的图像

使用self.navigationItem.leftBarButtonItems,这是一个UIBarButtonItem数组

let button = UIBarButtonItem()
let text = UIBarButtonItem()
self.navigationItem.leftBarButtonItems = [button, text]

相关内容

  • 没有找到相关文章