要在当前 UITableViewController 之上添加一个 customView,它必须是使用 'self.navigationController.view addSubview:customView' 的好方法,就像 Daniel 评论的那样。
但是,在实现用作导航栏的customView的情况下,Daniel的方式可能会导致在UITableViewController前后的其他navigationViewControllers上的默认或自定义navigationBar出现意外结果。
最好的简单方法是将 UITableViewController 转换为 UIViewController ,它对子视图的布局没有限制。但是,如果您正在为大量、长期遗留的 UITableViewController 代码而苦苦挣扎,那么情况就完全不同了。我们没有任何转换时间。
在这种情况下,您可以简单地劫持 UITableViewController 的 tableView 并解决整个问题。
我们应该知道的最重要的事情是UITableViewController的'self.view.superview'是nil,'self.view'是UITableView本身。
首先,劫持 UITableVIew。
UITableView *tableView = self.tableView;
然后,用新的 UIView 替换 'self.view'(现在是 UITableView),这样我们就可以无限制地布局 customView。
UIView *newView = UIView.new;
newView.frame = tableView.frame;
self.view = newView;
然后,将我们之前劫持的 UITableView 放到新的 self.view 上。
[newView addSubview:tableView];
tableView.translatesAutoresizingMaskIntoConstraints = NO;
[tableView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
[tableView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
[tableView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
[tableView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
现在,我们可以在 UITableViewController 上的这个全新的花哨的“self.view”上做任何我们想做的事情。
带一个自定义视图,然后添加为子视图。
UIView *myNaviBar = UIView.new;
[myNaviBar setBackgroundColor:UIColor.cyanColor];
[self.view addSubview:myNaviBar];
myNaviBar.translatesAutoresizingMaskIntoConstraints = NO;
[myNaviBar.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
[myNaviBar.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor].active = YES;
[myNaviBar.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor].active = YES;
[myNaviBar.heightAnchor constraintEqualToConstant:90].active = YES;
gif