UISearchBar修改placeholder - 2021

最近项目中用到了系统自带的UISearchBar,应UI设计师要求需要修改placeholder的文字颜色,网上全部都是几年前的老版本了,但是iOS13之后苹果要求不可以再使用,否则会崩溃。老版本如下:

//会崩溃
UITextField * searchField = [_searchBar valueForKey:@"_searchField"];
[searchField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];  [searchField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

使用新的方法,不会崩溃,拿来分享大家
新的修改方法如下:

//iOS13之后新方法
UITextField * searchField = [_homeSearchBar valueForKey:@"_searchTextField"];
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"搜索关键词" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithRGBHex:0xA1A7A8 alpha:0.5],NSFontAttributeName:searchField.font}];
        searchField.attributedPlaceholder = attrString;

你可能感兴趣的:(UISearchBar修改placeholder - 2021)