ios UISearchBar:更改输入域的背景色

r6hnlfcb  于 2023-08-08  发布在  iOS
关注(0)|答案(5)|浏览(112)

我正在尝试改变UISearchBar输入栏的背景颜色。它是一个圆形的视图,你可以在这里输入文本进行搜索,默认颜色是白色。我想换成灰色的
我试探着:

for (UIView *subView in searchBar.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
        UITextField *textField = (UITextField *)subView;
        [textField setBackgroundColor:[UIColor grayColor]];
    }

字符串
但它不工作:)
我还尝试插入一个图像视图到TextField,但似乎圆形视图是分开的TextField。有线索吗

8iwquhpp

8iwquhpp1#

=)

for (UIView *subView in _searchBar.subviews) {
    for(id field in subView.subviews){
        if ([field isKindOfClass:[UITextField class]]) {
            UITextField *textField = (UITextField *)field;
            [textField setBackgroundColor:[UIColor grayColor]];
        }
    }
}

字符串

suzh9iv8

suzh9iv82#

看看函数:

[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal];

字符串

vjhs03f7

vjhs03f73#

在Swift 2和iOS 9中,您可以调用:

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey()

字符串
Swift 3:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey()

2ul0zpep

2ul0zpep4#

Swift 3中的解决方案:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
        txfSearchField.borderStyle = .none
        txfSearchField.backgroundColor = .lightGray
}

字符串

ergxz8rk

ergxz8rk5#

以swift4中的扩展为例:

extension UISearchBar {

    var input : UITextField? {

        return findInputInSubviews(of: self)
    }

    func findInputInSubviews(of view: UIView) -> UITextField? {
        guard view.subviews.count > 0 else { return nil }
        for v in view.subviews {
            if v.isKind(of: UITextField.self) {
                return v as? UITextField
            }
            let sv = findInputInSubviews(of: v)
            if sv != nil { return sv }
        }
        return nil
    }
}

字符串
使用方法:

searchBar?.input?.layer.borderColor = color.cgColor

相关问题