自定义搜索栏

时间:2016-04-11 07:37:11

标签: ios objective-c xcode uisearchbar

我正在设计一个搜索栏。我需要搜索栏在图像中看起来像一个。试过几种但没有变化的方法。非常感谢。

screen shot

将帖子 使用Richard的代码后看到图像,它看起来像这样。我希望灰色很清晰。

screen shot

4 个答案:

答案 0 :(得分:4)

self.searchBarIBOutlet。您也可以动态创建它。

self.searchBar.layer.borderWidth = 2.0;
self.searchBar.layer.borderColor = [UIColor brownColor].CGColor;
self.searchBar.layer.cornerRadius = 15.0;
self.searchBar.barTintColor = [UIColor colorWithRed:255/255.0 green:246/255.0 blue:241/255.0 alpha:1.0];
self.searchBar.backgroundColor = [UIColor clearColor];

UITextField *textField = [self.searchBar valueForKey:@"_searchField"];
textField.textColor = [UIColor brownColor];
textField.placeholder = @"Search";
textField.leftViewMode = UITextFieldViewModeNever; //hiding left view
textField.backgroundColor = [UIColor colorWithRed:255/255.0 green:246/255.0 blue:241/255.0 alpha:1.0];
textField.font = [UIFont systemFontOfSize:18.0];
[textField setValue:[UIColor brownColor] forKeyPath:@"_placeholderLabel.textColor"];

UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 30)];
imgview.image = [UIImage imageNamed:@"searchIcon.png"]; //you need to set search icon for textfield's righ view

textField.rightView = imgview;
textField.rightViewMode = UITextFieldViewModeAlways;

输出:

enter image description here

答案 1 :(得分:0)

您可以使用一些自定义解决方案(它更适合自定义) 例如SSSearchBar或尝试找一些类似的

答案 2 :(得分:0)

if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
                textfield.textColor = UIColor.blue
                if let backgroundview = textfield.subviews.first {
                    // Background color
                    backgroundview.backgroundColor = UIColor.white
                    // Rounded corner
                    backgroundview.layer.cornerRadius = 14;
                    backgroundview.clipsToBounds = true;
                }
            }

答案 3 :(得分:0)

这是我的搜索栏

enter image description here

我使用以下代码进行了创建,搜索栏样式为默认

let searchIcon = Asset.icSearch.image
searchBar.setImage(searchIcon, for: .search, state: .normal)

let clearIcon = Asset.icDelete.image
searchBar.setImage(clearIcon, for: .clear, state: .normal)

if let textField = searchBar.getTextField() {
    textField.font = UIFont.systemFont(ofSize: 16)
    textField.backgroundColor = .white
}

searchBar.backgroundImage = UIImage()
searchBar.layer.borderColor = Asset.highlight.color.cgColor
searchBar.layer.borderWidth = 1
searchBar.layer.cornerRadius = 5

在iOS 13中,您可以使用“ searchTextField”获取TextField,但必须在iOS 12中编写一些代码。

extension UISearchBar {

    func getTextField() -> UITextField? {
        if #available(iOS 13.0, *) {
            return self.searchTextField
        } else {
            // Fallback on earlier versions
            let textField = subviews.first(where: { $0 is UITextField }) as? UITextField
            return textField
        }
    }
}