if #available(iOS 11, *) {
let view = UIView()
view.frame = CGRect(x: 20, y: 0, width: 70, height: 50)
let btn: UIButton = UIButton(frame: CGRect(x:-14, y: 0, width: 30, height: 27))
btn.setBackgroundImage(UIImage(named: "BackArrow"), for: UIControlState());
btn.addTarget(self, action: #selector(ExampleController.barBtnBackAction), for: UIControlEvents.touchUpInside)
btn.center = CGPoint(x: btn.center.x,y :view.center.y)
let tap = UITapGestureRecognizer(target: self, action: #selector(ExampleController.barBtnBackAction))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
view.backgroundColor = UIColor.black
view.addSubview(btn)
let leftButtonItem = UIBarButtonItem(customView: view)
self.navigationItem.leftBarButtonItem = leftButtonItem
}
我正在使用此代码在iOS 11的导航栏中设置回按钮,但它不能正常工作?用户在点击后退按钮时出现问题我无法使用默认设置,因为我想要自定义操作,在iOS 11之前我正在使用此代码: - (在iOS 10下面给出)它工作正常。
let barBtnNeg = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: self, action: nil)
barBtnNeg.width = -15.0
let btn: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 27))
btn.setBackgroundImage(UIImage(named: "BackArrow"), for: UIControlState());
btn.addTarget(self, action: #selector(ExampleController.btnBackAction), for: UIControlEvents.touchUpInside)
let barBtnBack = UIBarButtonItem(customView: btn)
self.navigationItem.leftBarButtonItems = [barBtnNeg, barBtnBack]
如果我使用此代码,后向箭头图像向右移动(对齐错误),如果我减少帧的x轴,静止图像不会移位,所以我必须使用上面的代码(如果#available(iOS 11) ,*))。
所有修复后退按钮问题的解决方案(导航栏)使用自定义图像,自定义选择器(操作)和自定义对齐?
答案 0 :(得分:1)
为导航控制器添加此类
class NavigationBar: UINavigationBar {
override func layoutSubviews() {
super.layoutSubviews()
for subview in self.subviews {
let stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame.origin.y = -20
subview.frame.size.height = 64
}
}
}
}
创建你需要的导航栏
let navigationBar = NavigationBar(frame: CGRect(origin: CGPoint(x: 0,
y: 20),
size: CGSize(width: view.frame.width,
height: 40)))
navigationBar.backgroundColor = UIColor(red: 46.0/255.0, green: 135.0/255.0, blue: 245.0/255.0, alpha: 1.0)
navigationBar.isTranslucent = false
let button1 = UIButton()
button1.setImage(UIImage(named: "Back"), for: UIControlState())
button1.addTarget(self, action: #selector (goBack(_:)), for: UIControlEvents.touchUpInside)
button1.frame = CGRect(x: 0, y: 5, width: 20, height: 20)
let barButton1 = UIBarButtonItem(customView: button1)
self.navigationItem.leftBarButtonItem = barButton1
navigationBar.items = [navigationItem]
self.view .addSubview(navigationBar)