修改UITextField的placeHolder文字颜色的三种方法


修改TextField的占位文字的三种方法

第一种 :通过TextField的attributedPlaceholder属性修改占位文字颜色

例如:

NSAttributedString *attr = [[NSAttributedString  alloc]initWithString:@"搜索位置"attributes:@{NSForegroundColorAttributeName:[[UIColor whiteColor]}];  
self.searchTextField.attributedPlaceholder = attr;
第二种 :通过继承UItextfield,然后重写-(void)drawPlaceholderInRect:(CGRect)rect 方法修改

例如:

// 修改占位文字颜色
-(void)drawPlaceholderInRect:(CGRect)rect {
  // 计算占位文字的 Size
  CGSize placeholderSize = [self.placeholder sizeWithAttributes:
                            @{NSFontAttributeName : self.font}];
  
  
  CGRect drawRect = CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height);
  
  NSDictionary *attributes = @{NSForegroundColorAttributeName:[[UIColor whiteColor] colorWithAlphaComponent:0.8],NSFontAttributeName : self.font};
  
  [self.placeholder drawInRect:drawRect withAttributes:attributes];
} 
第三种 :通过KVC的方式
// 'self'指的是UITextfield
[self setValue:[[UIColor whiteColor] colorWithAlphaComponent:0.8] forKeyPath:@"_placeholderLabel.textColor"];

通过KVC的方式有一定风险,如果系统更新,官方文档中修改了一些控件的属性名称,则会导致程序崩溃


文章作者: 小小学生
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小学生 !
评论
  目录