自定义UISearchBar上下线条无法隐藏,求解决方法
解决方法
要彻底移除UISearchBar中的多余线条,你需要针对SearchBar本身和内部的搜索文本框做两处关键修改:
- 清除SearchBar默认背景:设置
backgroundImage为空图片,直接去掉SearchBar自带的背景层和分隔线条。 - 取消搜索文本框边框:将文本框的
borderStyle设为.none,消除文本框的边框线条。
修改你SearchBarView里的createSearchBar()方法,添加这两行核心代码:
private func createSearchBar() -> UISearchBar { let searchBar = UISearchBar() searchBar.placeholder = " Search" searchBar.searchTextField.font = UIFont(name: "MarkPro", size: 15) searchBar.searchTextField.backgroundColor = .clear // 新增代码:移除默认背景与文本框边框 searchBar.backgroundImage = UIImage() searchBar.searchTextField.borderStyle = .none let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField let imageV = textFieldInsideSearchBar?.leftView as! UIImageView imageV.image = imageV.image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate) imageV.tintColor = UIColor(hexString: "FF6E4E") return searchBar }
你之前尝试的背景色设置可以保留,但这两处修改才是解决线条问题的核心。修改后,那些多余的线条就会完全消失。
内容的提问来源于stack exchange,提问作者Tambanco
相关产品推荐
相关产品推荐

