iOS开发之自定义UITextField

一. UITextField的基本使用

  1. 设置光标颜色
// 设置光标颜色
self.tintColor=[UIColorwhiteColor];
  1. 设置输入文字颜色
// 设置输入文字颜色
self.textColor=[UIColorwhiteColor];
  1. 通过代理设置开始输入和结束输入时占位文字的颜色
    一般情况下最好不要UITextField自己成为代理或者监听者
// 开始编辑
[self addTarget:self action:@selector(textDidBeginEdit)forControlEvents:UIControlEventEditingDidBegin];
// 结束编辑
[self addTarget:self action:@selector(textDidEndEdit)forControlEvents:UIControlEventEditingDidEnd];

//修改UITextField占位文字颜色
/方法一/
监听实现方法: 通过设置attributedPlaceholder

// attributedPlaceholder属性修改
-(void)setPlaceholderColor:(UIColor*)color
{
      NSMutableDictionary*attrDict=[NSMutableDictionarydictionary];
      attrDict[NSForegroundColorAttributeName]=color;
      NSAttributedString*attr=  [[NSAttributedStringalloc]initWithString:self.placeholder attributes:attrDict];
      self.attributedPlaceholder=attr;
}

/方法二/
//通过KVC拿到UITextField的占位label就可修改颜色

-(void)setPlaceholderLabelColor:(UIColor*)color
{
      UILabel*placeholderLabel=[self valueForKeyPath:@"placeholderLabel"];
      placeholderLabel.textColor=color;
}

二. 通过runtime来设置UITextField占位文字颜色

给UITextField添加一个占位文字颜色属性,而给系统类添加属性,就必须使用runtime来实现, 分类只能生成属性名

具体实现

  1. 给UITextField添加一个分类, 声明一个placeholderColor属性
#import
@interfaceUITextField   (Placeholder)
      // UITextField添加占位文字颜色属性
      @propertyUIColor*placeholderColor;
@end
  1. 实现placeholderColor属性的setter和getter方法
    setter方法
-(void)setPlaceholderColor:(UIColor*)placeholderColor
{
      // 关联属性
      objc_setAssociatedObject(self,(__bridgeconstvoid*)(placeholderColorName),placeholderColor,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
      // 通过KVC获取占位文字label属性(拿到lable就可以设置textColor)
      UILabel*placeholderLabel=[self valueForKeyPath:@"placeholderLabel"];
      placeholderLabel.textColor=placeholderColor;
}

getter方法

-(UIColor*)placeholderColor
{
      // 返回关联属性
      returnobjc_getAssociatedObject(self,(__bridgeconstvoid*)(placeholderColorName));
}
  1. 自定义setPlaceholder:并与系统setPlaceholder:方法交换
  • 交换系统setPlaceholder:设置占位文字和自定义my_setPlaceholder:方法
  • 交换原因:如果外界使用先设置了占位颜色,再设置占位文字,设置颜色时没有文字设置不成功
  • 交换设置占位文字方法,外界调用系统方法设置占位文字时,会自动调用自定义的设置占位文字方法,再调用系统设置占位文字方法,在自定义设置占位文字方法中自动设置占位文字颜色
-(void)my_setPlaceholder:(NSString*)placeholder
{
        [self my_setPlaceholder:placeholder];
        self.placeholderColor=self.placeholderColor;
}

在+(void) load方法中交换

+(void)load
{
        // 1.获取系统setPlaceholder:方法
       Methodsys=class_getInstanceMethod(self,@selector(setPlaceholder:));
        // 2.获取自定义my_setPlaceholder:方法
        Methoddefined=class_getInstanceMethod(self,@selector(my_setPlaceholder:));
        // 3.交换方法
        method_exchangeImplementations(sys,defined);
}
原文地址:https://www.cnblogs.com/Xfsrn/p/5063199.html