我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。
我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。
有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?
我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。
我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。
有没有一种方法来改变一个UITextField的占位符文本颜色使用Swift?
当前回答
Swift 3(可能是2),你可以覆盖didSet占位符在UITextField子类上应用属性,这样:
override var placeholder: String? {
didSet {
guard let tmpText = placeholder else {
self.attributedPlaceholder = NSAttributedString(string: "")
return
}
let textRange = NSMakeRange(0, tmpText.characters.count)
let attributedText = NSMutableAttributedString(string: tmpText)
attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)
self.attributedPlaceholder = attributedText
}
}
其他回答
您可以使用带属性的字符串设置占位符文本。只需要把你想要的颜色传递给属性参数。
斯威夫特5:
let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)
斯威夫特3:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)
年长的迅速:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSForegroundColorAttributeName: UIColor.white]
)
用于更改占位符文本颜色的Objective C代码。
首先导入这个objc/runtime类-
#进口< objc / >
然后替换文本字段名称- Ivar Ivar = class_getinstancvariable ([UITextField类],"_placeholderLabel"); UILabel *placeholderLabel = object_getIvar(YourTxtField, ivar); placeholderLabel。textColor = [UIColor whiteColor];
对于Swift 4.0, X-code 9.1版本或iOS 11,您可以使用以下语法来拥有不同的占位符颜色
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
对于目标C:
UIColor *color = [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1.0];
emailTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Friend's Email" attributes:@{NSForegroundColorAttributeName: color}];
迅速:
emailTextField.attributedPlaceholder = NSAttributedString(string: "Friend's Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
在Swift中这样使用,
let placeHolderText = textField.placeholder ?? ""
let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
textField.attributedPlaceholder = str
在Objective C中
NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;