通常自定义的leftBarButtonItems距离左侧边距有十万八千里元,让人看见就要反胃,但苹果就是这么吊,就是要你自定义的就必须这么丑!下面的方法目前可以解决这个问题。
- 先自定义一个UIButton:
import UIKit
class JKNavigationItemCustomView: UIButton {
var alignmentRectInsetsOverride = UIEdgeInsets.zero
override var alignmentRectInsets: UIEdgeInsets {
if UIEdgeInsetsEqualToEdgeInsets(alignmentRectInsetsOverride, UIEdgeInsets.zero) {
return super.alignmentRectInsets
}else {
return self.alignmentRectInsetsOverride
}
}
}
然后在ViewController中自定义leftBarButtonItems
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
let offset: CGFloat = 8
let backBtn = JKNavigationItemCustomView(type: .custom) //JKNavigationItemCustomView
let backBtnW: CGFloat = 22.0
let backBtnH: CGFloat = 42.0
backBtn.frame = CGRect(x: 0, y: 0, width: backBtnW, height: backBtnH)
backBtn.setImage(UIImage(named: "backbarbutton"), for: .normal)
backBtn.addTarget(self, action: #selector(baseBackButtonClick(_ :)), for: .touchUpInside)
let backItem = UIBarButtonItem(customView: backBtn)
if #available(iOS 11.0, *) {
backBtn.alignmentRectInsetsOverride = UIEdgeInsetsMake(0, offset, 0, -offset)
backBtn.translatesAutoresizingMaskIntoConstraints = false
backBtn.widthAnchor.constraint(equalToConstant: backBtnW).isActive = true
backBtn.heightAnchor.constraint(equalToConstant: backBtnH).isActive = true
}
let fixSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixSpaceItem.width = -offset
navigationItem.leftBarButtonItems = [fixSpaceItem, backItem]
}
图片周边留有适量空白
44x80 66x120
网友评论