日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

iOS-改变UITextField的Placeholder颜色的三种方式

發布時間:2025/5/22 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 iOS-改变UITextField的Placeholder颜色的三种方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉自:http://blog.csdn.net/mazy_ma/article/details/51775670

有時,UITextField自帶的Placeholder的顏色太淺或者不滿足需求,所以需要修改,而UITextField沒有直接的屬性去修改Placeholder的顏色,所以只能通過其他間接方式去修改。

例如:系統默認的Placeholder顏色太淺

需要加深顏色,或者改變顏色

方法一:通過attributedPlaceholder屬性修改Placeholder顏色

CGFloat viewWidth = self.view.bounds.size.width;CGFloat textFieldX = 50;CGFloat textFieldH = 30;CGFloat padding = 30;UITextField *textField = [[UITextField alloc] init];textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH);textField.borderStyle = UITextBorderStyleRoundedRect; // 邊框類型textField.font = [UIFont systemFontOfSize:14];// 就下面這兩行是重點NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"請輸入占位文字" attributes:@{NSForegroundColorAttributeName:[UIColor redColor],NSFontAttributeName:textField.font}];textField.attributedPlaceholder = attrString;[self.view addSubview:textField];

方法二:通過KVC修改Placeholder顏色

UITextField *textField1 = [[UITextField alloc] init];textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);textField1.borderStyle = UITextBorderStyleRoundedRect;textField1.placeholder = @"請輸入占位文字";textField1.font = [UIFont systemFontOfSize:14];// "通過KVC修改占位文字的顏色"[textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];[self.view addSubview:textField1];

方法三:通過重寫UITextField的drawPlaceholderInRect:方法修改Placeholder顏色

1、自定義一個TextField繼承自UITextField
2、重寫drawPlaceholderInRect:方法
3、在drawPlaceholderInRect方法中設置placeholder的屬性

// 重寫此方法 -(void)drawPlaceholderInRect:(CGRect)rect {// 計算占位文字的 SizeCGSize placeholderSize = [self.placeholder sizeWithAttributes:@{NSFontAttributeName : self.font}];[self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes:@{NSForegroundColorAttributeName : [UIColor blueColor],NSFontAttributeName : self.font}]; }

總結:
1、當我們使用純代碼創建UITextField時,用第二種方法(KVC)修改占位文字顏色是最便捷的 。
2、當我們使用XIB或者Storyboard創建UITextField時,通過自定義UITextField,修改占位文字顏色是最適合的。
3、我們也可以在第三種重寫方法中,通過結合第二種方法中的KVC修改屬性來實現。

轉載于:https://www.cnblogs.com/wanghang/p/6298813.html

總結

以上是生活随笔為你收集整理的iOS-改变UITextField的Placeholder颜色的三种方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。