【发布时间】:2012-04-04 08:47:59
【问题描述】:
我有一个 UITextField,其中初始文本是“username.mysite.com”。已设置默认颜色(黑色)。
我希望“用户名”具有不同的颜色,例如灰色。有可能吗?
用户可以点击“清除按钮”,占位符为“url”。
【问题讨论】:
标签: iphone ios uitextfield
我有一个 UITextField,其中初始文本是“username.mysite.com”。已设置默认颜色(黑色)。
我希望“用户名”具有不同的颜色,例如灰色。有可能吗?
用户可以点击“清除按钮”,占位符为“url”。
【问题讨论】:
标签: iphone ios uitextfield
不能直接使用 UITextField 完成。您的两个基本选项是:
使用UIWebView 伪装成文本字段。这很容易,但在某些用例中可能会导致性能损失。
使用Core Text 显示一个适当配置的 NSAttributedString。尽管该链接似乎适用于 Mac OS,但 Core Text 也存在于 iOS 上。该框架非常强大,但学习曲线陡峭,并且不支持开箱即用的可编辑文本。但是,有各种开源库可能有助于入门(例如 DTCoreText.OHAttributedLabel)。
【讨论】:
不,使用默认设置是不可能的。
【讨论】:
您可以更改占位符的颜色,通过访问以下私有属性,它会向您显示警告,但它会很好地工作。
[aTextField setValue:[UIColor yellowColor]
forKeyPath:@"_placeholderLabel.textColor"];
还有另一种方法可以做到这一点,您可以使用自定义实现覆盖 drawPlaceholderInRect 方法。
【讨论】:
UITextField 有一个attributedText 属性,可以设置为任何你喜欢的颜色的NSAttributedString。例如:
// Create a string:
let attribString = NSMutableAttributedString(string: "username.mysite.com")
// Set the grey color to the "username" portion of the string (the black color is the default for the rest):
attribString.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: 0, length: 8))
// Set the attributed string to your text field:
textField.attributedText = attribString
【讨论】: