关于这个问题:How to change Back button text from within the child view controller?我正在寻找一种在用previousViewController.navigationItem.backBarButtonItem?.title = "New Title"
更改后退按钮标题后刷新导航栏的方法。
来自链接问题的(不太理想?)解决方案:
if let navigationController = self.navigationController {
navigationController.popViewControllerAnimated(false)
navigationController.pushViewController(self, animated: false)
}
修改
显然,更改图层框会强制导航栏刷新。不是解决方案,而是一种较便宜的(?)解决方法,我想:
if let navigationController = self.navigationController {
navigationController.navigationBar.layer.frame.insetInPlace(dx: 0.1, dy: 0)
navigationController.navigationBar.layer.frame.insetInPlace(dx: -0.1, dy: 0)
}
答案 0 :(得分:5)
在尝试各种方法刷新之后,我发现这是最难看的解决方案似乎有效(至少在iOS 10上):
guard let navigation = navigationController,
!(navigation.topViewController === self) else {
return
}
let bar = navigation.navigationBar
bar.setNeedsLayout()
bar.layoutIfNeeded()
bar.setNeedsDisplay()
尝试了其他方法:
navigationBar
的文档明确禁止)答案 1 :(得分:0)
这对我有用
_ = navigationController.view.snapshotView(afterScreenUpdates: true)
答案 2 :(得分:0)
UIButton *leftbtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
[leftbtn addTarget:self action:@selector(city:) forControlEvents:UIControlEventTouchUpInside];
[leftbtn setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
leftbtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[leftbtn sizeToFit];
self.citybtn = leftbtn;
UIBarButtonItem* cityBtn = [[UIBarButtonItem alloc] initWithCustomView:leftbtn];
UIBarButtonItem *left_fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
left_fixedSpaceBarButtonItem.width = -17;
self.navigationItem.leftBarButtonItems = @[left_fixedSpaceBarButtonItem,cityBtn];
........
当你改变时
[self.citybtn setTitle:city forState:UIControlStateNormal];
[self.citybtn sizeToFit];
答案 3 :(得分:-1)
一个解决方案是拥有一个函数,它通过删除/隐藏后退按钮并使用navigationItem.leftBarButtonItem
属性在其位置显示自定义UIBarButtonItem来完全更改UIBarButtonItem。肯定不理想,但按钮不打算在VC生命周期中改变,所以我想你可以试试。从这个意义上讲,没有“正确”的方式,因为这不被视为标准行为。
当我将此函数添加到示例View Controller上的按钮时,它对我有用:
func changeBackButton() {
navigationItem.hidesBackButton = true
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Test", style: .plain, target: self, action: #selector(test))
}