ios - 在 Swift 4 中自定义 UISearchBar
<p><ul>
<li>我需要删除搜索栏的背景。</li>
<li>输入文本的部分(白色)使其更高。</li>
<li>在白色部分周围加上绿色边框。</li>
<li>自定义字体。</li>
</ul>
<p>我需要这个:</p>
<p> <img src="/image/R8gwP.png" alt="Picture 1"/> </p>
<p>我所取得的成就是这样的:</p>
<p> <img src="/image/Jk7pv.png" alt="Picture 2"/> </p>
<p>我的代码:</p>
<pre><code>@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.layer.borderColor = #colorLiteral(red: 0.2352941176, green: 0.7254901961, blue: 0.3921568627, alpha: 1)
self.searchBar.layer.borderWidth = 1
self.searchBar.clipsToBounds = true
self.searchBar.layer.cornerRadius = 20
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>尝试使用此代码:</p>
<pre><code>class JSSearchView : UIView {
var searchBar : UISearchBar!
override func awakeFromNib()
{
// the actual search barw
self.searchBar = UISearchBar(frame: self.frame)
self.searchBar.clipsToBounds = true
// the smaller the number in relation to the view, the more subtle
// the rounding -- https://www.hackingwithswift.com/example-code/calayer/how-to-round-the-corners-of-a-uiview
self.searchBar.layer.cornerRadius = 5
self.addSubview(self.searchBar)
self.searchBar.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 20)
let trailingConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -20)
let yConstraint = NSLayoutConstraint(item: self.searchBar, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraints()
self.searchBar.backgroundColor = UIColor.clear
self.searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
self.searchBar.tintColor = UIColor.clear
self.searchBar.isTranslucent = true
// https://stackoverflow.com/questions/21191801/how-to-add-a-1-pixel-gray-border-around-a-uisearchbar-textfield/21192270
for s in self.searchBar.subviews.subviews {
if s is UITextField {
s.layer.borderWidth = 1.0
s.layer.cornerRadius = 10
s.layer.borderColor = UIColor.green.cgColor
}
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
// the half height green background you wanted...
let topRect = CGRect(origin: .zero, size: CGSize(width: self.frame.size.width, height: (self.frame.height / 2)))
UIColor.green.set()
UIRectFill(topRect)
}
}
</code></pre>
<p>要使用它,请将自定义 View 拖放到您的 xib 或 Storyboard文件中,然后将自定义类类型设置为类的名称 (<code>JSSearchView</code>)。</p></p>
<p style="font-size: 20px;">关于ios - 在 Swift 4 中自定义 UISearchBar,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/48480316/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/48480316/
</a>
</p>
页:
[1]