Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 更改UISearchBar中UItextField中图标的颜色大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我正在尝试在搜索控制器中自定义搜索栏的外观. 设置背景和文本颜色工作正常但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和x按钮. 我发现这个Objective-C代码应该做我想要的但是我很难将它翻译成Swift: (编辑:跳到工作Swift 3解决方案的第一个答案.) UITextField *searchBarTextField = [self.searchDisplayCont
@H_675_6@
@H_675_6@
我正在尝试在搜索控制器中自定义搜索栏的外观.

设置背景和文本颜色工作正常但我没有找到一种方法来更改文本字段中的图标的颜色,特别是放大镜和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

大佬总结

以上是大佬教程为你收集整理的swift – 更改UISearchBar中UItextField中图标的颜色全部内容,希望文章能够帮你解决swift – 更改UISearchBar中UItextField中图标的颜色所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
猜你在找的Swift相关文章