我想在导航控制器的rightbarbuttonitem上设置共享按钮。我不想添加自定义图像,我想使用Xcode提供的共享按钮图像。这就是我在情节提要中的做法。我设置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.setTitle("RightButton", for: .normal)
button.setTitleColor(tintColor, for: .normal)
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)
}
您需要使用systemicon选项进行共享操作
let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAction(sender:)))
navigationItem.rightBarButtonItem = share