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

  • 修改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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容