swift – 更改UISearchBar中UItextField中图标的颜色
发布时间:2020-12-14 04:50:26 所属栏目:百科 来源:网络整理
导读:我正在尝试在搜索控制器中自定义搜索栏的外观. 设置背景和文本颜色工作正常但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和x按钮. 我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift: (编辑:跳到工作Swift 3解决方案的
我正在尝试在搜索控制器中自定义搜索栏的外观.
设置背景和文本颜色工作正常但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和x按钮. 我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift: (编辑:跳到工作Swift 3解决方案的第一个答案.) UITextField *searchBarTextField = [self.searchDisplayController.searchBar valueForKey:@"_searchField"]; // Magnifying glass icon. UIImageView *leftImageView = (UIImageView *)searchBarTextField.leftView; leftImageView.image = [LeftImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; leftImageView.tintColor = [UIColor whiteColor]; // Clear button UIButton *clearButton = [searchBarTextField valueForKey:@"_clearButton"]; [clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal]; clearButton.tintColor = [UIColor whiteColor]; 我试图翻译成Swift: let textField = searchController.searchBar.valueForKey("searchField") as! UITextField // These two work fine. textField.backgroundColor = UIColor.blackColor() textField.textColor = UIColor.blackColor() var glassIcon = textField.leftView // This would work. //glassIcon.hidden = true // This does not have any effect. //glassIcon?.tintColor = UIColor.whiteColor() // My attempt to translate,but it gives an error. glassIcon.image? = UIImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) var clearButton = textField.valueForKey("clearButton")! clearButton.setImage(clearButton.imageWithRenderingMode(.AlwaysTemplate),forState: .Normal) // This gives the error: "Cannot assign to property: 'clearButton' is immutable clearButton.tintColor = UIColor.whiteColor() // Sorry for the weird formatting,it glitches here in the editor. leftView似乎没有图像属性.如何像Objective-C代码那样访问该属性? 解决方法
这是解决方案:
// Text field in search bar. let textField = searchController.searchBar.value(forKey: "searchField") as! UITextField let glassIconView = textField.leftView as! UIImageView glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate) glassIconView.tintColor = UIColor.white let clearButton = textField.valueForKey("clearButton") as! UIButton clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate),for: .normal) clearButton.tintColor = UIColor.white (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |