如何删除iOS 11上UISearchController
下的行?
我使用以下代码添加了UISearchController
:
navigationItem.searchController = searchController
但在这之后,它下面有一条奇怪的线:
任何关于如何删除线条或至少选择其颜色的建议都将非常感激。
答案 0 :(得分:1)
一个hacky解决方案,但我现在最好的解决方案是添加一条与暗线重叠的白线视图:
let lineView = UIView(frame: CGRect(x: 0, y: searchController.searchBar.frame.height-4, width: view.bounds.width, height: 1))
lineView.backgroundColor = .white
searchController.searchBar.addSubview(lineView)
答案 1 :(得分:1)
这是另一种解决方案,虽然很弱,但是在特定的用例中可能会有用。
extension UISearchController {
var hairlineView: UIView? {
guard let barBackgroundView = self.searchBar.superview?.subviews.filter({ String(describing: type(of: $0)) == "_UIBarBackground" }).first
else { return nil }
return barBackgroundView.subviews.filter({ $0.bounds.height == 1 / self.traitCollection.displayScale }).first
}
}
有了该扩展名,您只需在视图控制器的viewWillLayoutSubviews
方法中编写以下代码:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// Remove hairline from the searchBar.
self.navigationItem.searchController?.hairlineView?.isHidden = true
}
请注意,此解决方案确实很弱,并且可能会随将来的iOS更新而中断。
此外,$0.bounds.height == 1 / self.traitCollection.displayScale
是不安全的,我建议您使用a proper float comparison method。
答案 2 :(得分:0)
如果将其添加为子视图,则在按后退或前进到另一页时会发现故障。这可以改善您的解决方案@budidino
let lineView = UIView(frame: .zero)
lineView.backgroundColor = .white
searchController.searchBar.addSubview(lineView)
lineView.translatesAutoresizingMaskIntoConstraints = false
lineView.leadingAnchor.constraint(equalTo: searchController.searchBar.leadingAnchor).isActive = true
lineView.trailingAnchor.constraint(equalTo: searchController.searchBar.trailingAnchor).isActive = true
lineView.bottomAnchor.constraint(equalTo: searchController.searchBar.bottomAnchor, constant: 1).isActive = true
lineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
答案 3 :(得分:0)
在iOS11中
@interface UISearchController (Additions)
- (void)hideHairLineView;
@end
@implementation UISearchController (Additions)
- (void)hideHairLineView{
UIView *barBackgroundView = self.searchBar.superview.subviews.firstObject;
for(UIView *v in barBackgroundView.subviews) {
if ([v isKindOfClass:[UIImageView class]]) {
UIImageView *imgView= (UIImageView *)v;
if (imgView.frame.size.height <= 1.0) {
[imgView setHidden:YES];
}
}
}
}
在viewWillLayoutSubviews
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
[self.navigationItem.searchController hideHairLineView];
}
在iOS13中
来自viewDidLoad
添加
[self.navigationController setDelegate:self];
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
[viewController.navigationController.navigationBar.viewForLastBaselineLayout setBackgroundColor:[UIColor clearColor]];
}