gpt4 book ai didi

swift - 快速搜索带有圆角半径的栏

转载 作者:行者123 更新时间:2023-11-28 05:38:09 26 4
gpt4 key购买 nike

Example Image

我想创建一个像上图一样的 View 。它有一个带有圆角半径的搜索栏。但是当我尝试创建时,我无法制作带有圆角半径的搜索栏。我也无法制作带有圆角半径的搜索栏的文本字段。我已经在 viewDidAppear 方法中编写了所有代码。没关系,否则我必须将它写在 viewWillLayourSubview 中。这样我就能做出准确的与此图像相同的搜索栏。我还希望搜索图标稍微靠右。

我的代码是:

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)

for subView in searchBar.subviews {


for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
var bounds: CGRect
var placeHolder = NSMutableAttributedString()
let Name = "Search"
placeHolder = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica", size: 15.0)!])


placeHolder.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range:NSRange(location:0,length:Name.count))

textField.attributedPlaceholder = placeHolder

if let leftView = textField.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)

leftView.frame.size.width = 15.0
leftView.frame.size.height = 15.0
leftView.tintColor = UIColor.gray

}
textField.layer.cornerRadius = 50.0

bounds = textField.frame
bounds.size.width = searchBar.frame.width
bounds.size.height = searchBar.frame.height
textField.bounds = bounds
textField.borderStyle = UITextField.BorderStyle.roundedRect

searchBar.backgroundImage = UIImage()
textField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

}
}
}
}*

最佳答案

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)

for subView in searchBar.subviews {
if !subView.subviews.contains(where: { $0 as? UITextField != nil }) { continue }
guard let textField = subView.subviews.first(where: { $0 as? UITextField != nil }) as? UITextField else { return }

let placeholder = NSMutableAttributedString(
string: "Search",
attributes: [.font: UIFont(name: "Helvetica", size: 15.0)!,
.foregroundColor: UIColor.gray
])
textField.attributedPlaceholder = placeholder
textField.borderStyle = UITextField.BorderStyle.roundedRect

textField.layer.cornerRadius = textField.frame.size.height / 2
textField.layer.masksToBounds = true
textField.textColor = .white
textField.backgroundColor = .lightGray
}

searchBar.barTintColor = .white
searchBar.backgroundColor = .white
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}

在您链接的图片中看起来并不完全一样,但实际上比您编写的代码更适合 Apple 设计并且工作得更好。

对于任何更复杂的东西,我建议创建一个自定义的 UISearchBar 子类。

注意 Apple 的 Human Interface Guidelines ,因此 AppStore 可能不会接受任何过于疯狂/与默认设置不同的内容。

关于swift - 快速搜索带有圆角半径的栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57938828/

26 4 0