国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS中修改UITextField占位符字體顏色的方法總結

2020-07-26 03:12:26
字體:
來源:轉載
供稿:網友

前言

最近學了UITextField控件, 感覺在里面設置占位符非常好, 給用戶提示信息, 于是就在想占位符的字體和顏色能不能改變呢?下面是小編的一些簡單的實現,有需要的朋友們可以參考。

修改UITextField的占位符文字顏色主要有三個方法:

1、使用attributedPlaceholder屬性

@property(nullable, nonatomic,copy) NSAttributedString  *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil

2、重寫drawPlaceholderInRect方法

- (void)drawPlaceholderInRect:(CGRect)rect;

3、修改UITextField內部placeholderLaber的顏色

[textField setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];

以下是詳細的實現過程

給定場景,如在注冊登錄中,要修改手機號和密碼TextField的placeholder的文字顏色。

效果對比


使用前


使用后

使用attributedPlaceholder

自定義GYLLoginRegisterTextField類,繼承自UITextField;實現awakeFromNib()方法,如果使用storyboard,那么修改對應的UITextField的CustomClassGYLLoginRegisterTextField即可

具體代碼如下:

#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];  //設置光標顏色 //修改占位符文字顏色 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];}@end

重寫drawPlaceholderInRect方法

與方法一同樣,自定義GYLLoginRegisterTextField,繼承自UITextField,重寫drawPlaceholderInRect方法,后續相同

代碼如下:

#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];  //設置光標顏色}- (void)drawPlaceholderInRect:(CGRect)rect{ NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; attrs[NSFontAttributeName] = self.font; //畫出占位符 CGRect placeholderRect; placeholderRect.size.width = rect.size.width; placeholderRect.size.height = rect.size.height; placeholderRect.origin.x = 0; placeholderRect.origin.y = (rect.size.height - self.font.lineHeight) * 0.5; [self.placeholder drawInRect:placeholderRect withAttributes:attrs]; //或者 /* CGPoint placeholderPoint = CGPointMake(0, (rect.size.height - self.font.lineHeight) * 0.5); [self.placeholder drawAtPoint:placeholderPoint withAttributes:attrs]; */}@end

修改UITextField內部placeholderLaber的顏色

使用KVC機制,找到UITextField內部的修改站位文字顏色的屬性:placeholderLaber.textColor

代碼如下:

#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];  //設置光標顏色 //修改占位符文字顏色 [self setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];}@end

第三種方法比較簡單,建議可以將此封裝:擴展UITextField,新建category,添加placeholderColor屬性,使用KVC重寫setget方法。

總結

以上就是這篇文章的全部內容了,希望能對大家開發iOS有所幫助,如果有疑問大家可以留言交流。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大连市| 平阴县| 依兰县| 巨鹿县| 旌德县| 平山县| 桦川县| 平乡县| 洛宁县| 安庆市| 门头沟区| 申扎县| 大关县| 安阳市| 抚顺市| 正镶白旗| 达州市| 申扎县| 梁山县| 义乌市| 平阴县| 丹东市| 阿坝县| 原阳县| 黑河市| 灵台县| 永年县| 金川县| 黄大仙区| 治多县| 漳浦县| 油尖旺区| 当阳市| 博客| 鄂尔多斯市| 青神县| 蓬安县| 南城县| 东丽区| 云阳县| 志丹县|