【问题标题】:UITextField attributedPlaceholder has no effectUITextField 属性占位符没有效果
【发布时间】:2013-02-22 19:20:06
【问题描述】:

我正在尝试将文本字段中的占位符设置为斜体,并且由于我的应用程序针对的是 iOS 6.0 或更高版本,因此决定使用 attributedPlaceholder 属性而不是滚动更多自定义内容。代码如下:

NSString *plString = @"optional";
NSAttributedString *placeholder = [[NSAttributedString alloc] initWithString:plString
        attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-LightItalic" size:15]}];
for (UITextField *t in myTextfields){
    t.placeholder = plString;
    t.attributedPlaceholder = placeholder;
}

但占位符的样式仍然不是斜体,而是与常规文本相同,只是更暗。要使NSAttributedString 工作,我缺少什么?

【问题讨论】:

  • 我可以重现您的问题,我认为这是 iOS 中的一个错误。

标签: ios uitextfield nsattributedstring


【解决方案1】:

正如沃伦所说,目前无法按照您尝试的方式完成样式设置。一个好的解决方法是按照您希望占位符的外观设置文本字段的字体属性,然后在用户开始输入时更改文本字段的字体。看起来占位符和文本是不同的字体。

您可以通过创建文本字段的委托并像这样使用 shouldChangeCharactersinRange 来做到这一点:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{    
    // If there is text in the text field
    if (textField.text.length + (string.length - range.length) > 0) {
        // Set textfield font
        textField.font = [UIFont fontWithName:@"Font" size:14];
    } else {
        // Set textfield placeholder font (or so it appears)
        textField.font = [UIFont fontWithName:@"PlaceholderFont" size:14];
    }

    return YES;
}

【讨论】:

    【解决方案2】:

    这几乎可以肯定是一个错误。 documentation for the attributedPlaceholder property 声称无论前景色属性如何,都将使用灰色绘制字符串,但事实并非如此:您可以同时设置前景色和背景色。不幸的是,字体属性似乎被剥离并恢复为系统字体。

    作为一种解决方法,我建议覆盖 drawPlaceholderInRect: 并自己绘制占位符。此外,您应该就此提交 Radar,并包含一个演示该错误的最小示例项目。

    【讨论】:

    【解决方案3】:

    我自己只是偶然发现了这个问题。显然,占位符将采用分配给文本字段的任何字体。只需设置文本字段的字体就可以了。

    对于其他的一切,比如占位符的颜色,我还是会回到attributedPlaceholder

    【讨论】:

    • 很棒的答案。为我工作!
    【解决方案4】:

    iOS8/9/Swift 2.0 - 工作示例

    func colorPlaceholderText(){
        var multipleAttributes = [String : NSObject]()
        multipleAttributes[NSForegroundColorAttributeName] = UIColor.appColorCYAN()
        //OK - comment in if you want background color
        //multipleAttributes[NSBackgroundColorAttributeName] = UIColor.yellowColor()
        //OK - Adds underline
        //multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.StyleDouble.rawValue
    
    
        let titleString = "Search port/country/vessel..."
        let titleAttributedString = NSAttributedString(string: titleString,
            attributes: multipleAttributes)
    
    
        self.textFieldAddSearch.attributedPlaceholder = titleAttributedString
    }
    

    【讨论】:

    • 这适用于颜色。但不适用于字体本身
    猜你喜欢
    • 2012-12-27
    • 2013-03-30
    • 2015-12-21
    • 2013-04-27
    • 2016-09-19
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    相关资源
    最近更新 更多