以编程方式设置栏按钮“系统项目”

Programattically set barbutton " System Item"

我想在导航控制器的rightbarbuttonitem 上设置分享按钮。 我不想添加自定义图像,我想使用 Xcode.This 提供的共享按钮图像,这就是我在情节提要中的做法。 我设置 Style ,并将 System_Item 设置为 Action.

现在的问题是,如果我以编程方式创建 barbuttonitem,我该如何以编程方式设置 System_Item

let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton

您可以创建一个扩展来执行此操作 ->

public extension UIViewController {

    func setRightBarButtonItem(tintColor: UIColor = AppColor.barButtonColor) {
        let button = UIButton(type: .system)

        button.tintColor = tintColor
        button.setImage(UIImage(.action), for: .normal) // <-- Set system icon to button

        button.translatesAutoresizingMaskIntoConstraints = false

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap))
        button.addGestureRecognizer(tapGesture)

        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }

    @objc func tap() {
        // Do stuff
    }
}

然后在你的 ViewController

override func viewDidLoad() {
    super.viewDidLoad()
    setRightBarButtonItem()

    // OR

    setRightBarButtonItem(tintColor: .blue)
}

使用没有版本控制的系统图标的 UIImage 扩展

extension UIImage {

  public convenience init?(_ systemItem: UIBarButtonItem.SystemItem) {

    guard let sysImage = UIImage.imageFrom(systemItem: systemItem)?.cgImage else {
      return nil
    }

    self.init(cgImage: sysImage)
  }

  private class func imageFrom(systemItem: UIBarButtonItem.SystemItem) -> UIImage? {

    let sysBarButtonItem = UIBarButtonItem(barButtonSystemItem: systemItem, target: nil, action: nil)

    let toolBar = UIToolbar()
    toolBar.setItems([sysBarButtonItem], animated: false)
    toolBar.snapshotView(afterScreenUpdates: true)

    if let buttonView = sysBarButtonItem.value(forKey: "view") as? UIView{
      for subView in buttonView.subviews where subView is UIButton {
        let button = subView as! UIButton
        let image = button.imageView!.image!
        return image
      }
    }
    return nil
  }
}

您需要使用 UIBarButtonSystemItemAction 选项直接获取分享操作

   let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor
    navigationItem.rightBarButtonItem = share

并像

一样处理操作
@objc func shareAction(sender: UIBarButtonItem) {

}