ios开发小技巧iOS日常收集

UITextField-修改占位文字和光标的颜色,大小

2015-08-16  本文已影响13303人  YotrolZ

一.设置占位文字的颜色

方法一:利用富文本


/** 手机号输入框 */
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建一个富文本对象
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    // 设置富文本对象的颜色
    attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
    // 设置UITextField的占位文字
    self.phoneTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"手机号" attributes:attributes];
    
}

方法二:利用Runtime获取私有的属性名称,利用KVC设置属性

// 设置占位文字的颜色为红色(注意下面的'self'代表你要修改占位文字的UITextField控件)
[self setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
// 只调用一次(自定义UITextField)
+ (void)initialize {

    [self getIvars];
    
}

// 获取私有变量名称
+ (void)getIvars {
    
    unsigned int count = 0;
    
    Ivar *ivars = class_copyIvarList([UITextField class], &count);
    
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        
        NSLog(@"%s----%s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
    }
}

查看打印,找出可能的属性名称,试试便知;

#import "YCTextField.h"
#import <objc/runtime.h>

#define YCplaceholderTextColor @"_placeholderLabel.textColor"

@implementation YCTextField

+ (void)initialize {

    [self getIvars];
    
}

// 获取私有变量名称
+ (void)getIvars {
    
    unsigned int count = 0;
    
    Ivar *ivars = class_copyIvarList([UITextField class], &count);
    
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        
        NSLog(@"%s----%s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
    }
}

- (void)awakeFromNib {

    // 设置光标的颜色
    self.tintColor = self.textColor;
}

// 获取到焦点
- (BOOL)becomeFirstResponder {

    // 利用运行时获取key,设置占位文字的颜色
    [self setValue:self.textColor forKeyPath:YCplaceholderTextColor];
    
    return [super becomeFirstResponder];
}

// 失去焦点
- (BOOL)resignFirstResponder {

    // 利用运行时获取key,设置占位文字的颜色
    [self setValue:[UIColor grayColor] forKeyPath:YCplaceholderTextColor];
    
    return [super resignFirstResponder];
}

@end

方法三.将占位文字上去(重写- (void)drawPlaceholderInRect:(CGRect)rect;)

- (void)drawPlaceholderInRect:(CGRect)rect
{

    [[UIColor orangeColor] set];
    
    [self.placeholder drawInRect:rect withFont:[UIFont systemFontOfSize:20]];
}

二.设置光标颜色

// 设置光标的颜色
self.tintColor = [UIColor redColor];

三.设置占位文字的偏移

//控制placeHolder的位置,左右缩20
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
    
    //return CGRectInset(bounds, 20, 0);
    CGRect inset = CGRectMake(bounds.origin.x+50, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
    return inset;
}
上一篇 下一篇

猜你喜欢

热点阅读