iOS语法技巧iOS DeveloperiOS 开发

添加分类修改UITextField的占位文字颜色

2016-01-23  本文已影响404人  小虎哥

-详情参考YotrolZ的UITextField-修改占位文字和光标的颜色,大小

Simulator Screen Shot 2016年1月23日 下午7.42.39.png

在这里我通过给UITextField添加分类 提供"placeholderColor"属性直接在添加UITextField时使用

#import <UIKit/UIKit.h>
@interface UITextField (Extension)
/** 占位文字颜色 */
@property(nonatomic, strong) UIColor *placeholderColor;
@end

在这里只会生成placeholderColor的setter和gettet方法的声明,不会生成方法的实现和_成员变量

#import "UITextField+Extension.h"

@implementation UITextField (Extension)

- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    BOOL change = NO;
    //保证有占位文字
    if (self.placeholder == nil) {
        self.placeholder = @" ";
        change = YES;
    }
    //设置占位文字颜色
    [self setValue:placeholderColor forKeyPath:@"placeholderLabel.textColor"];
    
    //恢复原状
    if (change) {
        self.placeholder = nil;
    }
}

-(UIColor *)placeholderColor{
    return [self valueForKey:@"placeholderLabel.textColor"];
}

@end

这里通过setter和gettet方法的的实现设置占位文字颜色,利用的Runtime私有属性,KVC设置属性

  unsigned int outCount = 0;
    
    Ivar *var = class_copyIvarList([UITextField class], &outCount);
    
    for (int i = 0; i < outCount; i++) {
        Ivar ivar = var[i];
        NSLog(@"%s", ivar_getName(ivar));
    }
    
    free(var);

通过以上代码就可以拿到私有的成员属性

hu.jpg
上一篇下一篇

猜你喜欢

热点阅读