这里有另一个解决方案,虽然不太强大,但在特定的用例中可能会很有用。
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
是不安全的,我建议您使用适当的浮点数比较方法。
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)
如果你将其添加为子视图,当按返回或前往另一页时可能会出现故障。这可以改进你的解决方案@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
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]];
}