带边框的自定义searchBar

时间:2017-10-06 18:37:50

标签: swift uisearchbar searchbar

以前曾问过这个问题的变化,但没有一个解决方案对我有用。我已经把tableViewHeader变成了searchBar,这是我到目前为止所做的。

我的代码如下所示:

    override func viewDidLoad() {
    super.viewDidLoad()
    configureSearchBar()
    self.tableView.separatorColor = UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0)
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

func configureSearchBar() {
    searchController.searchBar.delegate = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.hidesNavigationBarDuringPresentation = false
    searchController.searchBar.placeholder = "Search Companies"
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar
    searchController.searchBar.barTintColor = UIColor.white

    //makes border for search box and gives color and rounded
    //searchController.searchBar.layer.borderColor = UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0).cgColor
    //searchController.searchBar.layer.borderWidth = 2.0
    //searchController.searchBar.layer.cornerRadius = 15.0

}

我试图建立这个但是到目前为止我一直没有成功

我正在尝试构建

Screen Shot

如果我试试这个:

searchController.searchBar.layer.borderColor = UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0).cgColor
    searchController.searchBar.layer.borderWidth = 1.0
    searchController.searchBar.layer.cornerRadius = 15.0
    searchController.searchBar.clipsToBounds = true

它看起来像这样,这正是我正在寻找的。

最终结果如何

Screen Shot

感谢您在高级

中提供的帮助

2 个答案:

答案 0 :(得分:2)

我能够让它像这样工作。需要更改的标题大小不是更改标题的大小,而是搜索栏中文本框的大小。

func configureSearchBarTextField() {
    for subView in searchController.searchBar.subviews  {
        for subsubView in subView.subviews  {
            if let textField = subsubView as? UITextField {
                var bounds: CGRect
                bounds = textField.frame
                bounds.size.height = 35 //(set height whatever you want)
                textField.bounds = bounds
                textField.layer.cornerRadius = 5
                textField.layer.borderWidth = 1.0
                textField.layer.borderColor = UIColor(red:0.00, green:0.87, blue:0.39, alpha:1.0).cgColor
                textField.backgroundColor = UIColor.white
            }
        }
    }
}

答案 1 :(得分:0)

这对我有用

self.searchBar.layer.borderColor = UIColor.cyan.cgColor
self.searchBar.layer.borderWidth = 1
self.searchBar.layer.cornerRadius = 5.0
self.searchBar.clipsToBounds = true

并在委托中更新标题的高度:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 200
}