Swift UISearchBar笔记

let SearchBarView = UISearchBar()
//初始化在父控件中的位置,和大小
SearchBarView.frame  = CGRect(x:60,y:40,width:200,height:40)
//背景色
SearchBarView.backgroundColor = UIColor.clear
//tool.mainColor是父控件的背景色,看起来与父控件融为一体,没有黑色线条
SearchBarView.barTintColor = tool.mainColor
//提示文字
SearchBarView.placeholder = "请输入搜索内容"
//在父控件中的唯一标示,值随便取,别重复就行
SearchBarView.tag = 123
//边框宽度
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)
//方法一的图片大小有点怪,暂时没找到方法修改
//更换放大镜图片方法二,修改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
效果图
Swift UISearchBar笔记_第1张图片
image.png

你可能感兴趣的:(Swift UISearchBar笔记)