修改UITextField的placeholder 字体颜色大小

2018-10-24  本文已影响0人  叫我小黑

UITextField 是 iOS 开发中常用的控件,它有一个placeholder属性,也就是占位文字,默认占位文字颜色是70% gray。有时,UITextField自带的Placeholder的颜色大小太浅或者不满足需求,所以需要修改,而UITextField没有直接的属性去修改Placeholder的颜色大小,所以只能通过其他间接方式去修改。

方式一
NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; // 创建属性字典
  attrs[NSFontAttributeName] = [UIFont systemFontOfSize:17]; // 设置font
  attrs[NSForegroundColorAttributeName] = [UIColor greenColor]; // 设置颜色
  NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"夏虫不可以语冰" attributes:attrs]; // 初始化富文本占位字符串
  self.textField.attributedPlaceholder = attStr;
方式二
- (void)drawPlaceholderInRect:(CGRect)rect
{
    [self.placeholder drawInRect:CGRectMake(0, 2, rect.size.width, 25) withAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:16.0],
                                        NSForegroundColorAttributeName : [UIColor blueColor],
                                     }];
}
方式三
 UITextField *textField1 = [[UITextField alloc] init];
    textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);
    textField1.borderStyle = UITextBorderStyleRoundedRect;
    textField1.placeholder = @"请输入占位文字";
    textField1.font = [UIFont systemFontOfSize:14];
    // "通过KVC修改占位文字的颜色"
    [textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:textField1];
上一篇 下一篇

猜你喜欢

热点阅读