使用带下划线的自定义UISearchBar

时间:2019-06-07 15:12:05

标签: swift uisearchbar

我需要使UISearchBar无边界。我需要在末尾(右上角)插入图片,删除边框并加下划线。 UISearchBar应该看起来像图片中的样子。请帮忙。我是新手,我不知道该怎么做。

enter image description here

1 个答案:

答案 0 :(得分:0)

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

Custom Search Bar

现在,打开UITextField的出口,并将以下代码添加到自定义视图的类文件中。查看代码

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

现在,在您的UIViewController的{​​{1}}方法中,添加以下代码以编程方式添加自定义搜索栏。

viewDidLoad

输出: Output

我希望这会对您有所帮助。