iOS开发设置UISearchBar的输入背景框、提示文字等

开发中经常需要用到搜索框,当使用系统搜索框的时候,可以改变搜索框的背景图片、提示文字颜色、取消按钮字体颜色、放大镜图片等,swift代码如下:

//搜索框
        let searchBar = UISearchBar(frame: CGRect(x: 8, y: 0, width: self.view.frame.size.width - 16, height: 35))
        searchBar.searchBarStyle = .Minimal
        searchBar.placeholder = "请输入关键字"
        searchBar.setImage(UIImage(named: "test_sousuo"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal) //替换收缩放大镜
        searchBar.setImage(UIImage(named: "test_quxiao"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal) //输入的时候,右侧的清除按钮
        searchBar.setSearchFieldBackgroundImage(UIImage(named: "sousuokuang"), forState: UIControlState.Normal) //输入背景框
        //改变提示文字颜色
        let sbTextField = searchBar.valueForKey("searchField") as? UITextField //首先取出textfield
        let sbPlaceholderLabel = sbTextField?.valueForKey("placeholderLabel") as? UILabel //然后取出textField的placeHolder
        sbPlaceholderLabel?.textColor = UIColor.redColor() //改变颜色

objective-c代码:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 260, self.view.frame.size.width - 16, 35)];
    searchBar.searchBarStyle = UISearchBarStyleMinimal;
    searchBar.placeholder = @"请输入关键字";
    [searchBar setImage:[UIImage imageNamed:@"test_sousuo"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal]; //替换收缩放大镜
    [searchBar setImage:[UIImage imageNamed:@"test_quxiao"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal]; //输入的时候,右侧的清除按钮
    [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"sousuokuang"] forState:UIControlStateNormal]; //输入背景框
    //改变提示文字颜色
    UITextField *sbTextField = [searchBar valueForKey:@"searchField"]; //首先取出textfield
    sbTextField.textColor = [UIColor blueColor]; //输入的颜色
    UILabel *sbPlaceholderLabel = [sbTextField valueForKey:@"placeholderLabel"]; //然后取出textField的placeHolder
    sbPlaceholderLabel.textColor = [UIColor redColor]; //改变颜色
    [self.view addSubview:searchBar];

取消按钮,swift写法:

//取出取消按钮
        let cancelBtn = searchBar.valueForKey("cancelButton") as? UIButton
        cancelBtn?.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)

objective-c写法

//取消按钮有显示的时候
    searchBar.showsCancelButton = YES;
    UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"]; //首先取出cancelBtn
    //这样就可以随便设置这个按钮了
    [cancelBtn setTitle:@"搜索" forState:UIControlStateNormal];

效果图
这里写图片描述
这里写图片描述
带右侧按钮
这里写图片描述
这里写图片描述

展开阅读全文

没有更多推荐了,返回首页