答案 0 :(得分:2)
可能的解决方案。您可以创建UIBarButton项目的扩展名。 例如:
import UIKit
extension UIBarButtonItem {
convenience init (image: UIImage?, target: Any?, action: Selector?) {
let button = UIButton(type: .custom)
button.imageView?.contentMode = .scaleAspectFit
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.addTarget(target, action: action!, for: .touchUpInside)
button.setImage(image, for: UIControlState.normal)
button.imageEdgeInsets = UIEdgeInsets(top: 7.0, left: 7.0, bottom: 7.0, right: 7.0)
if #available(iOS 9.0, *) {
button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true
button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
}
self.init(customView: button)
}
}
然后在viewDidLoad
方法中使用它:
let rightButton = UIBarButtonItem(image: UIImage(named: "example"), target: self, action: #selector(exampleAction(sender:)))
self.navigationItem.rightBarButtonItem = rightButton
答案 1 :(得分:0)
您可以使用现有的UIBarButtonItem
便利init
方法:
convenience init(image: UIImage?, style: UIBarButtonItemStyle, target: Any?, action: Selector?)
使用style
= .plain(无边框)。
请参阅https://developer.apple.com/documentation/uikit/uibarbuttonitem/1617163-init
然后,要通知您的UINavigationController在您的UIViewController位于导航堆栈顶部时显示您的按钮,请设置视图控制器的navigationItem.rightBarButtonItems
属性:
(myViewController.navigationItem.rightBarButtonItems = [<your items>]