更改UITextField的placeholder文字颜色的5种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Z1591090/article/details/68941275

更改UITextField的placeholder文字颜色的5种方法 ##更改UITextField的placeholder文字颜色的5种方法

想要达到的目标是:一个页面上有多个UITextField,当用户聚焦某textField时,该文本框的placeholder的文字会灰色变为白色,当文本框失去焦点时,placeholder颜色从白色再变回灰色。

1.放置UILabel

最简单最笨的方法是在每个textField里放一个UILabel来充当placeholder,当该textField聚焦时,让placeholder的文字会灰色变为白色,失焦后从白色再变回灰色。这种方法需要对每个UILabel和TextField拖线,通过监听键盘通知或者UITextField的代理来获悉textField是否聚焦,然后写一堆if语句来判断。

2.修改textField.attributedPlaceholder属性

//通过NSAttributedString来更改placeholder颜色。此种方法比较麻烦的是,需要知道页面上所有的textField什么时候聚焦,什么时候失焦(有两种方法:A.监听键盘弹出的通知 B.通过UITextField的代理方法textFieldDidBeginEditing),然后再判断哪个是白色,哪个是灰色。如果页面上textField非常多,就需要写很多的if语句。

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:@"手机号" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

self.phoneTextField.attributedPlaceholder = attrString;
  1. 利用UITextField的子类重写drawPlaceholderInRect:方法

    具体实现见代码:

复制代码
//该方法的好处是不用获取Xib中textField的引用,不用拖线,直接将Xib中textField的class改为自定义类即可。以后有任何textField想要改变placeholder的颜色,直接定义为该类即可。但还是需要自己监控UITextField是否聚焦。

import “WZCustomPlaceholderTextField.h”

@implementation WZCustomPlaceholderTextField
/**
@interface NSString(NSStringDrawing) NSString的分类
- (CGSize)sizeWithAttributes:(nullable NSDictionary

import “WZTextField.h”

@implementation WZTextField
//调用顺序1 (从xib创建时调用)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
}
return self;
}
//调用顺序2 (从xib创建时调用)
- (void)awakeFromNib {

}

//调用顺序3 (无论xib还是纯代码创建都会调用)
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.tintColor = self.textColor; //设置光标颜色和文字颜色一样
}

  • (BOOL)becomeFirstResponder {
    [self setValue:[UIColor whiteColor] forKeyPath:@”_placeholderLabel.textColor”];
    return [super becomeFirstResponder];
    }

  • (BOOL)resignFirstResponder {
    [self setValue:[UIColor grayColor] forKeyPath:@”_placeholderLabel.textColor”];
    return [super resignFirstResponder];
    }

@end

猜你喜欢

转载自blog.csdn.net/Z1591090/article/details/68941275