自定义UISearchBar:试图摆脱search栏下面的1px黑线
我的问题已经在标题中指定了:我想摆脱UISearchBar底部绘制的黑线。 有任何想法吗? 
这是我的意思的图像:

更新 :
 我认为这行是UITableView的tableHeaderView 。 我仍然不知道如何删除它。 
 我通过添加subview到searchBar的视图堆栈来解决这个问题,如下所示: 
 CGRect rect = self.searchBar.frame; UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, rect.size.height-2,rect.size.width, 2)]; lineView.backgroundColor = [UIColor whiteColor]; [self.searchBar addSubview:lineView]; 
 这里, self.searchBar是我的控制器类的UISearchBar指针。 
尝试这个
  searchBar.layer.borderWidth = 1; searchBar.layer.borderColor = [[UIColor lightGrayColor] CGColor]; 
为什么:
 所以,我已经钻研了API,试图找出为什么会发生这种情况。 显然,谁写的UISearchBar API是光栅化到图像上的行,并将其设置为backgroundImage 。 
解:
 我提出了一个更简单的解决scheme,如果你想设置backgroundColor并摆脱细线: 
 searchBar.backgroundColor = <#... some color #> searchBar.backgroundImage = [UIImage new]; 
或者如果你只是需要一个没有细线的背景图片:
 searchBar.backgroundImage = <#... some image #> 
 我的UISearchBar顶部和底部都有0.5px黑色水平线。 我迄今为止摆脱它们的唯一方法是将其风格设置为Minimal : 
 mySearchBar.searchBarStyle = UISearchBarStyleMinimal; 
 controller.searchBar.layer.borderWidth = 1 controller.searchBar.layer.borderColor = UIColor(red: 255/255, green: 253/255, blue: 247/255, alpha: 1.0).CGColor 
根据Ayush的回答,回答Swift。
 在把UISearchBar放在那里之前,将tableHeaderView设置nil 。 
 如果这没有帮助,试着掩盖它。 首先将你的search栏添加到一个generics和适当大小的UIView (比如说“包装器”)作为子视图 
 CGRect frame = wrapper.frame; CGRect lineFrame = CGRectMake(0,frame.size.height-1,frame.size.width, 1); UIView *line = [[UIView alloc] initWithFrame:lineFrame]; line.backgroundColor = [UIColor whiteColor]; // or whatever your background is [wrapper addSubView:line]; [line release]; 
然后将其添加到tableHeaderView。
 self.tableView.tableHeaderView = wrapper; [wrapper release]; 
这个问题已经解决了,但也许我的解决scheme可以帮助别人。 我有一个类似的问题,除了我试图删除1px顶部边框。
 如果你的子类UISearchBar你可以覆盖这个框架。 
 - (void)setFrame:(CGRect)frame { frame.origin.y = -1.0f; [super setFrame:frame]; self.clipsToBounds = YES; self.searchFieldBackgroundPositionAdjustment = UIOffsetMake(0, 1.0f); } 
或者如果你想修复底部像素,你可以做这样的事情(未经testing)。
 - (void)setFrame:(CGRect)frame { frame.origin.y = 1.0f; [super setFrame:frame]; self.clipsToBounds = YES; self.searchFieldBackgroundPositionAdjustment = UIOffsetMake(0, -1.0f); } 
 只是为了简单起见, searchFieldBackgroundPositionAdjustment中的setFrame和setFrame 。 
 此外searchFieldBackgroundPositionAdjustment只需要重新居中search字段。 
UPDATE
 事实certificate,当searchBar处于活动状态时, tableView将从更新origin.y的位置移动1px。 这感觉有点奇怪。 我意识到解决scheme和设置一样简单, self.clipsToBounds = YES; 
警告。 这是一个黑客。 想知道更好,更正式的方式。
您可以使用小马debugging器来确定子视图中的哪个位置。 我认为你所看到的是一个名为“分隔符”的私有UIImageView
 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; for (UIView* view in self.searchBar.subviews) { if (view.frame.size.height == 1 && [view isKindOfClass:[UIImageView class]]) { view.alpha = 0; break; } } } 
 解决scheme为XCode 8.3.3 Swift 3.1  
 
您可以使用
  [[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"someImage.png"]forState:UIControlStateNormal]; 
在iOS 5 +摆脱线。