iOS設(shè)置TextField的placeholder的顏色锣笨,位置追逮,字體脚乡,光標(biāo)顏色
-
如果只是單純的想修改一下占位文字的的顏色字體
-
可以設(shè)置attributedPlaceholder屬性
UITextField *textField = [UITextField new]; NSString *placeholderString = @"占位文字"; NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString: placeholderString]; //占位文字字體顏色 [placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, placeholderString.length)]; //占位文字字體大小 [placeholder addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:15] range:NSMakeRange(0, placeholderString.length)]; textField.attributedPlaceholder = placeholder;
-
通過(guò)KVC訪問(wèn)內(nèi)部變量直接訪問(wèn)
textField.placeholder = @"請(qǐng)輸入你的QQ號(hào)"; [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
可以通過(guò)以上兩種方式直接改變textField的占位文字的顏色和字體
-
-
改變占位文字的位置,光標(biāo)的位置,文本顯示的位置,這個(gè)需要我們自定義一個(gè)textField,來(lái)重寫(xiě)它里面的一些方法,具體的可以根據(jù)自己的需要來(lái)定制
-
自定義textField的.h文件
#import <UIKit/UIKit.h> #import "UIColor+YS.h" @interface LYTextField : UITextField @end
-
自定義textField的.m文件
#import "LYTextField.h" @implementation LYTextField //通過(guò)代碼創(chuàng)建 - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setUpUI]; } return self; } //布局子控件 - (void)setUpUI{ //設(shè)置border self.layer.masksToBounds = YES; [self.layer setCornerRadius:14]; self.layer.borderWidth = 1; [self.layer setBorderColor:HEX(@"#D8D8D8").CGColor]; //字體大小 self.font = [UIFont fontWithName:@"PingFangSC-Regular" size:12]; //字體顏色 self.textColor = kAppColor33; //光標(biāo)顏色 self.tintColor= self.textColor; //占位符的顏色和大小 [self setValue:kAppColor99 forKeyPath:@"_placeholderLabel.textColor"]; [self setValue:[UIFont fontWithName:@"PingFangSC-Regular" size:12] forKeyPath:@"_placeholderLabel.font"]; } //控制placeHolder的位置 上邊界4 左14 -(CGRect)placeholderRectForBounds:(CGRect)bounds{ CGRect inset = CGRectMake(bounds.origin.x + 14, bounds.origin.y + 4, bounds.size.width -14, bounds.size.height - 5); return inset; } //控制顯示文本的位置 -(CGRect)textRectForBounds:(CGRect)bounds{ CGRect inset = CGRectMake(bounds.origin.x + 14, bounds.origin.y + 4, bounds.size.width - 14, bounds.size.height - 5); return inset; } //控制編輯文本的位置(光標(biāo)顯示的位置) -(CGRect)editingRectForBounds:(CGRect)bounds { CGRect inset = CGRectMake(bounds.origin.x + 14, bounds.origin.y + 4, bounds.size.width -14, bounds.size.height - 5); return inset; }
-