美文网首页iOS语法技巧iOS DeveloperiOS 开发
添加分类修改UITextField的占位文字颜色

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

作者: 小虎哥 | 来源:发表于2016-01-23 19:57 被阅读404次
  • 修改UITextField占位文字颜色常用方法
    • 1.通过富文本
    • 2.通过Runtime私有的属性,利用KVC设置属性
    • 3.通过- (void)drawPlaceholderInRect:(CGRect)rect画上去

-详情参考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设置属性

  • Runtime运行时的使用 导入头文件#import <objc/runtime.h>
  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

相关文章

网友评论

    本文标题:添加分类修改UITextField的占位文字颜色

    本文链接:https://www.haomeiwen.com/subject/vjerkttx.html