gpt4 book ai didi

swift - 制作带下划线的自定义 UISearchBar

转载 作者:行者123 更新时间:2023-11-30 10:42:25 27 4
gpt4 key购买 nike

我需要使UISearchBar没有边框。我需要在末尾(右上角)插入图片,删除周围的边框并添加下划线。 UISearchBar 应该如图所示。请帮忙。我是 swift 的新手,我不知道该怎么做。

enter image description here

最佳答案

创建自定义 xib View 并添加文本字段 View ,如下所示,就像您提供的图片一样。

Custom Search Bar

现在,取出 UITextField 的导出并在自定义 View 的类文件中添加以下代码。查看代码

class CustomSearchBar: UIView {

//------------------------------------------------------------------------------
// MARK:- Outlets
//------------------------------------------------------------------------------

@IBOutlet weak var txtSearch : UITextField!


//------------------------------------------------------------------------------
// MARK:- Abstract Method
//------------------------------------------------------------------------------

class func instantiateView() -> CustomSearchBar {
let customSearchBar = UINib(nibName: "CustomSearchBar", bundle: .main).instantiate(withOwner: self, options: nil)[0] as! CustomSearchBar

let uiView = UIView.init(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
let imageView = UIImageView(frame: CGRect(x: 0, y: 8, width: 24, height: 24))
imageView.image = #imageLiteral(resourceName: "icon_down_arrow").withRenderingMode(.alwaysTemplate)
imageView.tintColor = .blue
uiView.addSubview(imageView)

// Add right button
customSearchBar.txtSearch.rightViewMode = .always
customSearchBar.txtSearch.rightView = uiView

return customSearchBar
}
}

现在,在 UIViewControllerviewDidLoad 方法中添加以下代码,以编程方式添加自定义搜索栏。

class ViewController: UIViewController {

override func viewDidLoad() {

let customSearchBar = CustomSearchBar.instantiateView()
customSearchBar.translatesAutoresizingMaskIntoConstraints = false
customSearchBar.txtSearch.delegate = self

self.view.addSubview(customSearchBar)

customSearchBar.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
customSearchBar.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
customSearchBar.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
customSearchBar.heightAnchor.constraint(equalToConstant: 60).isActive = true
}
}

extension ViewController: UITextFieldDelegate {

func textFieldDidEndEditing(_ textField: UITextField) {

}

//------------------------------------------------------------------------------

func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {

}
}

输出: Output

希望这对您有帮助。

关于swift - 制作带下划线的自定义 UISearchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497015/

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