let SearchBarView = UISearchBar()
//初始化在父控件中的位置,和大小
SearchBarView.frame = CGRect(x:60,y:40,width:200,height:40)
//背景色
SearchBarView.backgroundColor = UIColor.clear
//tool.mainColor是父控件的背景色,看起來(lái)與父控件融為一體,沒(méi)有黑色線條
SearchBarView.barTintColor = tool.mainColor
//提示文字
SearchBarView.placeholder = "請(qǐng)輸入搜索內(nèi)容"
//在父控件中的唯一標(biāo)示,值隨便取,別重復(fù)就行
SearchBarView.tag = 123
//邊框?qū)挾?SearchBarView.layer.borderWidth = 0
//搜索框樣式
SearchBarView.searchBarStyle = UISearchBarStyle.minimal
//是否顯示Bookmark按鈕
SearchBarView.showsBookmarkButton = false
//是否顯示Cancel按鈕
SearchBarView.showsCancelButton = false
//添加到父控件中
TopView.addSubview(SearchBarView)
//獲取搜索框的輸入框
let searchField = SearchBarView.value(forKey: "searchField") as! UITextField
//改變搜索框的輸入框的輸入框的字體顏色
searchField.textColor = UIColor.white
//改變搜索框的輸入框的提示文字顏色,也就是搜索框提示文字的顏色
searchField.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
//更換“放大鏡”圖片方法一
SearchBarView.setImage(UIImage(named: "Search"),for: UISearchBarIcon.search, state: UIControlState.normal)
//方法一的圖片大小有點(diǎn)怪,暫時(shí)沒(méi)找到方法修改
//更換放大鏡圖片方法二,修改SearchBarView.value(forKey: "searchField")的左視圖
let btnsearchLeft:UIButton = UIButton(type:UIButtonType.custom)
btnsearchLeft.frame = CGRect(x:0,y:0,width:29,height:29)
btnsearchLeft.setBackgroundImage(UIImage(named:"Search"), for: UIControlState())
searchField.leftView = btnsearchLeft
searchField.leftViewMode = .always
效果圖

image.png