gpt4 book ai didi

ios - 在 Swift 4 中自定义 UISearchBar

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:04:59 24 4
gpt4 key购买 nike

  • 我需要删除搜索栏的背景。
  • 输入文本的部分(白色)使其更高。
  • 在白色部分周围加上绿色边框。
  • 自定义字体。

我需要这个:

Picture 1

我取得的成就是:

Picture 2

我的代码:

@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
}

最佳答案

尝试使用这段代码:

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([yConstraint, leadingConstraint, trailingConstraint])

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[0].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)
}
}

要使用它,将自定义 View 放入您的 xib 或 Storyboard文件中,并将自定义类类型设置为类的名称 (JSSearchView)。

关于ios - 在 Swift 4 中自定义 UISearchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48480316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com