纯代码在导航栏中实现搜索框

效果:

代码:

if let navigationController = self.navigationController {
            let searchBar = navigationController.navigationBar
            // 搜索文本框
            let searchField = UITextField(frame: CGRectMake(0, 0, navigationController.navigationBar.frame.size.width, searchBar.frame.size.height*0.7))
            searchField.clearButtonMode = UITextFieldViewMode.WhileEditing//文本框后面的清除按钮
            searchField.layer.cornerRadius = 15.0//圆角
            searchField.borderStyle = UITextBorderStyle.RoundedRect //解决设置圆角后,光标位置太靠前和边框重叠的问题
            searchField.layer.borderColor = UIColor.whiteColor().CGColor //设置边框颜色
            searchField.layer.borderWidth = 1.0 // 不设置长度看不到边框的颜色
            searchField.backgroundColor = UIColor.clearColor() // 设置背景色
            searchField.returnKeyType = UIReturnKeyType.Search // 键盘上右下角的按钮名称
            searchField.tintColor = UIColor.whiteColor()// 设置光标的颜色,默认是蓝色。同时后面清除按钮按住后的颜色也会同时修改。

            // 光标右移
            let leftPaddingView = UIView(frame: CGRectMake(0, 0, 10, 30))
            searchField.leftView = leftPaddingView;
            searchField.leftViewMode = UITextFieldViewMode.Always

            // 搜索按钮
            // 设置右边搜索按钮的一种方式,但这种好像不能设置大小
            //            let searchButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: "search:")
//            searchButton.image = UIImage(named: "btn_search")
//            searchButton.tintColor = UIColor.whiteColor() // 按钮默认是蓝色的,要给成和图片一致的颜色
//            searchButton.width = searchBar.frame.size.height*0.9
//            self.navigationItem.rightBarButtonItem = searchButton

            let searchButton2 = UIButton(frame:CGRectMake(0, 0, searchBar.frame.size.height*0.5, searchBar.frame.size.height*0.5))
            searchButton2.setBackgroundImage(UIImage(named: "btn_search"), forState: UIControlState.Normal)



            // searchBar的设置背景色
            searchBar.barTintColor = UIColor(netHex: APPRED) // 设置导航栏的背景色
            self.navigationItem.titleView = searchField
            //self.navigationItem.rightBarButtonItem = searchButton
            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: searchButton2)
            navigationController.navigationBar.clipsToBounds = true //去掉navigationBar下面的线            
        }
    ```
2015-11-11 19:3240