【问题标题】:Two different colors inside an UITextFieldUITextField 内有两种不同的颜色
【发布时间】:2012-04-04 08:47:59
【问题描述】:

我有一个 UITextField,其中初始文本是“username.mysite.com”。已设置默认颜色(黑色)。

我希望“用户名”具有不同的颜色,例如灰色。有可能吗?

用户可以点击“清除按钮”,占位符为“url”。

【问题讨论】:

    标签: iphone ios uitextfield


    【解决方案1】:

    不能直接使用 UITextField 完成。您的两个基本选项是:

    1. 使用UIWebView 伪装成文本字段。这很容易,但在某些用例中可能会导致性能损失。

    2. 使用Core Text 显示一个适当配置的 NSAttributedString。尽管该链接似乎适用于 Mac OS,但 Core Text 也存在于 iOS 上。该框架非常强大,但学习曲线陡峭,并且不支持开箱即用的可编辑文本。但是,有各种开源库可能有助于入门(例如 DTCoreText.OHAttributedLabel)。

    【讨论】:

      【解决方案2】:

      不,使用默认设置是不可能的。

      【讨论】:

        【解决方案3】:

        您可以更改占位符的颜色,通过访问以下私有属性,它会向您显示警告,但它会很好地工作。

        [aTextField setValue:[UIColor yellowColor] 
                    forKeyPath:@"_placeholderLabel.textColor"];
        

        还有另一种方法可以做到这一点,您可以使用自定义实现覆盖 drawPlaceholderInRect 方法。

        【讨论】:

        • 嗨,RIP,我想更改属性文本的颜色,而不是占位符。颜色只是“用户名”部分而不是整个文本。
        • 我认为这是不可能直接的,你可以检查以下线程 - stackoverflow.com/questions/2452356/…
        【解决方案4】:

        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
        

        【讨论】:

          猜你喜欢
          • 2015-08-05
          • 2011-09-24
          • 1970-01-01
          • 2016-03-15
          • 1970-01-01
          • 1970-01-01
          • 2021-11-14
          • 1970-01-01
          相关资源
          最近更新 更多