我正在尝试为导航栏创建自定义titleView。我能够在嵌入在导航控制器中的根视图控制器中设置titleView。
当我将第二个视图控制器推入堆栈并尝试为此视图控制器设置titleView时,它不起作用。 titleView快速出现并消失。当我回到上一个视图控制器时,这个titleView会很快出现并且现在也消失了。
有谁知道为什么会这样,或者如何正确设置titleView而不闪烁并消失?
class FirstViewController: UIViewController {
var titleView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
addTitleView()
}
func addTitleView() {
titleView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 44))
let companyLabel = UILabel(frame: CGRect(x: 0, y: 3, width: 150, height: 11))
companyLabel.text = "CPS Dashboard"
companyLabel.textColor = UIColor.grayColor()
companyLabel.textAlignment = .Center
companyLabel.font = UIFont.systemFontOfSize(9)
titleView.addSubview(companyLabel)
let titleLabel = UILabel(frame: CGRect(x: 0, y: 16, width: 150, height: 18))
titleLabel.text = "Dashboard"
titleLabel.textColor = UIColor.blackColor()
titleLabel.textAlignment = .Center
titleLabel.font = UIFont.systemFontOfSize(15)
titleView.addSubview(titleLabel)
navigationItem.titleView = titleView
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Show" {
let controller = segue.destinationViewController as! SecondViewController
controller.titleView = titleView
}
}
}
第二个viewcontroller:
class SecondViewController: UIViewController {
var titleView: UIView?
override func viewDidLoad() {
super.viewDidLoad()
if let titleView = titleView {
navigationItem.titleView = titleView
}
}
}
答案 0 :(得分:0)
我的解决方案很简单,而且有效:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let tv = navigationItem.titleView {
print("transform", tv.transform)) // is always identity
let bounds = tv.bounds
print("bounds", bounds) // its origin may not be zero.
tv.bounds = CGRect(origin: .zero, size: bounds.size)
print("new bounds", tv.bounds)
}
}
使用Xcode的视图调试器,您会发现titleView.bounds.origin不为零
如何让它再次发生,两个步骤:
1. UIViewController A和B; A有自定义navigationItem.titleView
,B在其navigationBar
中隐藏viewWillAppear()
;当B poped时,A.viewWillAppear()setNavigationBar(hidden:false,animated:true)
2.举起手来取消用户驱动的popViewController
然后你会发现,A navigationBar
是空白的。
答案 1 :(得分:0)
我遇到了同样的问题,但是以上解决方案都没有为我解决。我的问题是我将arr[1::2]
设置为''.join
。我想这会导致出现/消失,因为需要将其设置为translatesAutoresizingMaskIntoConstraints
才能将视图内部限制在导航栏中。
答案 2 :(得分:-2)
// show segment control in navigation bar instead of label
@interface XCtrl : UIViewController
{
UIView *barTitleView;
UISegmentedControl *barSegment;
}
@end
@implementation XCtrl
- (void)viewWillAppear:(BOOL)animated
{
UINavigationItem *navitem = self.tabBarController.navigationItem;
[barSegment removeFromSuperview];
// retain title view of previous controller and restore him when view disappears
barTitleView = navitem.titleView;
navitem.titleView = barSegment;
}
- (void)viewWillDisappear:(BOOL)animated
{
[barSegment removeFromSuperview];
UINavigationItem *navitem = self.tabBarController.navigationItem;
navitem.titleView = barTitleView;
}
@end