【问题标题】:iPhone UITextField - Change placeholder Font and Text ColoriPhone UITextField - 更改占位符字体和文本颜色
【发布时间】:2014-06-12 04:28:05
【问题描述】:

我有一个UITextField 我需要更改Placeholder 字体和颜色,我在drawRect 方法中调用下面的方法,

-(void) setFontColorForPlaceHolder
{
    for(id obj in [[self baseScrollView] subviews])
    {
        if([obj isKindOfClass:[UITextField class]])
        {
            [obj setAttributedPlaceholder:[[NSAttributedString alloc]initWithString:[obj placeholder] attributes:@{
                NSFontAttributeName:kFutura_Medium_14 ,NSForegroundColorAttributeName:[UIColor redColor]
            }]];
        }
    }
}

这里颜色正在改变,但字体没有设置。 setAttributedPlaceholder 有什么问题。

【问题讨论】:

  • 有很多可用的链接试试这个stackoverflow.com/questions/18244790/…
  • setAttributedPlaceholder 在 ios6 中不工作
  • @MitsBhadeshiya :是的,你是对的,它在 iOS7 中运行良好。那么在 iOS6 中该怎么做呢?
  • 你为什么从drawRect:调用这个代码?这根本不合适。
  • 设置UITextField 子视图的占位符不是绘制自定义视图的一部分。您应该在创建自定义视图时设置一次占位符,例如在其init... 方法中。自定义视图的drawRect: 应该只用于绘制视图的自定义内容(如果有)。如果您的自定义视图只有子视图而没有自定义绘图,您甚至不应该实现drawRect: 方法。

标签: ios objective-c uitextfield


【解决方案1】:

SWIFT 3 在您的自定义类中覆盖此:

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
     //set initial attributed placeholder color and font
     self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: placeholderTextFont])
     return bounds
}

【讨论】:

    【解决方案2】:

    适用于 iOS 6+

    [textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
    

    要为占位符设置字体,只需在编写 textholder 之前为 textfield 设置字体即可。

    textField.font = your font here;
    [textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
    textField.placeholder = "your placeholder string here...";
    

    【讨论】:

      【解决方案3】:

      我在 iOS 7.1 中进行测试,发现 NSFontAttributeName 没有对 UITextField 的占位符文本做任何事情。

      但是,当我更改 UITextField 本身的字体时,占位符文本字体也发生了变化:

      aUITextField.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:20.0f];
      

      【讨论】:

        猜你喜欢
        • 2010-11-23
        • 2018-09-19
        • 2012-05-16
        • 2012-04-12
        • 1970-01-01
        • 2011-11-11
        • 1970-01-01
        • 2017-05-18
        • 2013-02-04
        相关资源
        最近更新 更多