将图像和标签添加到UIBarButtonItem [复制]

问题描述 投票:1回答:1

这个问题在这里已有答案:

如何在leftBarButtonItem上的导航中添加图像和标签?

enter image description here

我已经为我的导航项目分配了一个图像,如下所示:

let notifButton  = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0) )

notifButton.setImage(UIImage(named: "notifications_white"), for: UIControlState.normal)
notifButton.addTarget(self, action: #selector(self.notifButtonCLicked), for: UIControlEvents.touchUpInside)

let leftBarButtonItem = UIBarButtonItem(customView: notifButton)
self.UIViewController?.navigationItem.leftBarButtonItem = leftBarButtonItem
ios swift uibarbuttonitem
1个回答
2
投票
let button =  UIButton(type: .custom)
          button.setImage(UIImage(named: "icon_right"), for: .normal)
          button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
          button.frame = CGRect(x: 0, y: 0, width: 53, height: 31)
          button.imageEdgeInsets = UIEdgeInsetsMake(-1, 32, 1, -32)//move image to the right
          let label = UILabel(frame: CGRect(x: 3, y: 5, width: 20, height: 20))
          label.font = UIFont(name: "Arial-BoldMT", size: 16)
          label.text = "title"
          label.textAlignment = .center
          label.textColor = .black
          label.backgroundColor =  .clear
          button.addSubview(label)
          let barButton = UIBarButtonItem(customView: button)
          self.navigationItem.rightBarButtonItem = barButton
© www.soinside.com 2019 - 2024. All rights reserved.