斯威夫特 4.1 (Xcode 9.4.1)
如果不知道alignmentRectInsets,可以先看这篇博客。
为了简化答案,我们需要对图像边缘插图进行一些调整。
extension UIImage {
func withInsets(_ insets: UIEdgeInsets) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: size.width + insets.left + insets.right,
height: size.height + insets.top + insets.bottom),
false,
self.scale)
let origin = CGPoint(x: insets.left, y: insets.top)
self.draw(at: origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
https://stackoverflow.com/a/32576128/6113158
由Stefan Kendall
这是如何使用它的示例。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar(with: backImage)
}
func setupNavBar(with backIcon: UIImage) {
navBarLeftImageInsects = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
if let backImage = backIcon.withInsets(navBarLeftImageInsects) {
navigationController?.navigationBar.backIndicatorImage = backImage
navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
}