IOS 小技巧:自定义 textField 的占位文本(placeholder)

  • 方法一
    使用 KVC 方式自定义 textField 的占位文本.
    示例代码
    UITextField *tf = [[UITextField alloc] init];
    tf.placeholder = @“占位文本”;
//textColor 和 textFont 为自定义的字体颜色字体尺寸
    [tf setValue:textColor forKeyPath:@"_placeholderLabel.textColor"];
    [tf setValue:[UIFont boldSystemFontOfSize:textFont] forKeyPath:@"_placeholderLabel.font"];
  • 方法二
    使用官方提供的 API 自定义 textFIeld

@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil


  示例代码
UITextField *tf = [[UITextField alloc] init];
tf.placeholder = @"占位文本";
NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
dictM[NSForegroundColorAttributeName] = [UIColor redColor];
dictM[NSFontAttributeName] = [UIFont systemFontOfSize:20];
NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:tf.placeholder attributes:dictM];
[tf setAttributedPlaceholder:attribute];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容