IPhone UITextField - изменить цвет текста заполнителя
Я хотел бы изменить цвет текста заполнителя, который я установил в своих элементах управления UITextField
, чтобы сделать его черным.
Я бы предпочел сделать это, не используя обычный текст в качестве заполнителя, и должен переопределить все методы для имитации поведения заполнителя.
Я верю, что если я переопределю этот метод:
- (void)drawPlaceholderInRect:(CGRect)rect
тогда я должен это сделать. Но я не уверен, как получить доступ к фактическому объекту-заполнителю из этого метода.
Ответы
Ответ 1
Вы можете переопределить drawPlaceholderInRect:(CGRect)rect
как таковой, чтобы вручную отобразить текст заполнителя:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
Ответ 2
С момента введения атрибутных строк в UIViews в iOS 6 можно назначить цвет текста заполнителя следующим образом:
if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}
Ответ 3
Легкая и безболезненная, может быть легкой альтернативой для некоторых.
_placeholderLabel.textColor
Не рекомендуется для производства, Apple может отклонить ваше представление.
![]()
Ответ 4
Вы можете изменить цвет текста Placeholder на любой цвет, который вы хотите, используя приведенный ниже код.
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
Ответ 5
Возможно, вы хотите попробовать таким образом, но Apple может предупредить вас о доступе к частному ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
Примечание
По словам Мартина Аллеуса, это больше не работает на iOS 7.
Ответ 6
Это работает в Swift <3.0:
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
Протестировано в iOS 8.2 и iOS 8.3 beta 4.
Свифт 3:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])
Свифт 4:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
Swift 4.2:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
Ответ 7
В Swift:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}
В Swift 4.0:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
Ответ 8
Swift 3.0 + раскадровка
Чтобы изменить цвет заполнителя в раскадровке, создайте расширение со следующим кодом. (не стесняйтесь обновлять этот код, если вы думаете, он может быть яснее и безопаснее).
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
return currentAttributedPlaceholderColor
}
set {
guard let currentAttributedString = attributedPlaceholder else { return }
let attributes = [NSForegroundColorAttributeName : newValue]
attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
}
}
}
![enter image description here]()
Версия Swift 4
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
Версия Swift 5
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
Ответ 9
Следующее только в iOS6 + (как указано в комментарии Alexander W):
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];
Ответ 10
С этим мы можем изменить цвет текста заполнителя текстового поля в iOS
[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
Ответ 11
Я уже сталкивался с этой проблемой. В моем случае приведенный ниже код является правильным.
Цель С
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
Для Swift 4.X
tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
Надеюсь, это может помочь вам.
Ответ 12
Почему бы вам просто не использовать метод UIAppearance
:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
Ответ 13
Также в вашем раскадровке без отдельной строки кода
![введите описание изображения здесь]()
Ответ 14
Для iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Надеюсь, что это поможет.
Примечание. Apple может отклонить (0,01% шансов) ваше приложение, поскольку мы обращаемся к частному API. Я использую это во всех своих проектах с двух лет, но Apple не просила об этом.
Ответ 15
Для разработчиков Xamarin.iOS я нашел это из этого документа
https://developer.xamarin.com/api/type/Foundation.NSAttributedString/
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red });
Ответ 16
Быстрая версия. Вероятно, это помогло бы кому-то.
class TextField: UITextField {
override var placeholder: String? {
didSet {
let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
self.attributedPlaceholder = placeholderString
}
}
}
Ответ 17
Для обработки вертикального и горизонтального выравнивания, а также цвета заполнителя в iOS7. drawInRect и drawAtPoint больше не используют текущий контекст fillColor.
https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html
Obj-C,
@interface CustomPlaceHolderTextColorTextField : UITextField
@end
@implementation CustomPlaceHolderTextColorTextField : UITextField
-(void) drawPlaceholderInRect:(CGRect)rect {
if (self.placeholder) {
// color of placeholder text
UIColor *placeHolderTextColor = [UIColor redColor];
CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];
CGRect drawRect = rect;
// verticially align text
drawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;
// set alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = self.textAlignment;
// dictionary of attributes, font, paragraphstyle, and color
NSDictionary *drawAttributes = @{NSFontAttributeName: self.font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : placeHolderTextColor};
// draw
[self.placeholder drawInRect:drawRect withAttributes:drawAttributes];
}
}
@end
Ответ 18
Категории FTW. Может быть оптимизирован для проверки эффективного изменения цвета.
#import <UIKit/UIKit.h>
@interface UITextField (OPConvenience)
@property (strong, nonatomic) UIColor* placeholderColor;
@end
#import "UITextField+OPConvenience.h"
@implementation UITextField (OPConvenience)
- (void) setPlaceholderColor: (UIColor*) color {
if (color) {
NSMutableAttributedString* attrString = [self.attributedPlaceholder mutableCopy];
[attrString setAttributes: @{NSForegroundColorAttributeName: color} range: NSMakeRange(0, attrString.length)];
self.attributedPlaceholder = attrString;
}
}
- (UIColor*) placeholderColor {
return [self.attributedPlaceholder attribute: NSForegroundColorAttributeName atIndex: 0 effectiveRange: NULL];
}
@end
Ответ 19
iOS 6 и более поздние UITextField
предлагают attributedPlaceholder
на UITextField
. iOS 3.2 и более поздние setAttributes:range:
предлагают setAttributes:range:
on NSMutableAttributedString
.
Вы можете сделать следующее:
NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;
Ответ 20
Переопределение drawPlaceholderInRect:
будет правильным, но оно не работает из-за ошибки в API (или документации).
Метод никогда не вызывается на UITextField
.
См. также drawTextInRect на UITextField не вызывается
Вы можете использовать решение digdog. Поскольку я не уверен, что это прошлое обзора Apple, я выбрал другое решение: Наложите текстовое поле на мою собственную метку, которая имитирует поведение замещающего.
Это немного грязно.
Код выглядит так (обратите внимание, что я делаю это внутри подкласса TextField):
@implementation PlaceholderChangingTextField
- (void) changePlaceholderColor:(UIColor*)color
{
// Need to place the overlay placeholder exactly above the original placeholder
UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
overlayPlaceholderLabel.opaque = YES;
overlayPlaceholderLabel.text = self.placeholder;
overlayPlaceholderLabel.textColor = color;
overlayPlaceholderLabel.font = self.font;
// Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
[self.superview addSubview:overlayPlaceholderLabel];
self.placeholder = nil;
}
Ответ 21
Iam new для xcode, и я нашел способ с тем же эффектом.
Я разместил uilabel вместо владельца места с нужным форматом и спрятал его в
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
switch (textField.tag)
{
case 0:
lblUserName.hidden=YES;
break;
case 1:
lblPassword.hidden=YES;
break;
default:
break;
}
}
Я соглашаюсь на свою работу, а не на реальное решение, но эффект был таким же, как и у этого link
ПРИМЕЧАНИЕ: Все еще работает на iOS 7: |
Ответ 22
Это решение для Swift 4.1
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
Ответ 23
Для тех, кто использует Monotouch (Xamarin.iOS), здесь Адам отвечает, переведен на С#:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}
Ответ 24
Лучшее, что я могу сделать для iOS7 и меньше:
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
return rect;
}
- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *color =RGBColor(65, 65, 65);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
} else {
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font];
}
}
Ответ 25
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
Ответ 26
в быстрой 3.X
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
в кратчайшие сроки 5
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
Ответ 27
Мне нужно было поддерживать выравнивание заполнителя, поэтому для меня было недостаточно ответа адама.
Чтобы решить эту проблему, я использовал небольшой вариант, который, я надеюсь, поможет некоторым из вас:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
Ответ 28
Для установки Attributed Text Place Placeholder с несколькими цветами
Просто укажите текст,
//txtServiceText is your Textfield
[email protected]"Badal/ Shah";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
_txtServiceText.attributedPlaceholder=mutable;
Выход: -
![введите описание изображения здесь]()
Ответ 29
Другая опция, которая не требует подкласса - оставьте пробел и поместите надпись поверх кнопки редактирования. Управляйте ярлыком так же, как вы управляете заполнителем (очистка, когда пользователь вводит что-либо..)
Ответ 30
В Свифт 3
import UIKit
let TEXTFIELD_BLUE = UIColor.blue
let TEXTFIELD_GRAY = UIColor.gray
class DBTextField: UITextField {
/// Tetxfield Placeholder Color
@IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAY
func setupTextField () {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",
attributes:[NSForegroundColorAttributeName: palceHolderColor])
}
}
class DBLocalizedTextField : UITextField {
override func awakeFromNib() {
super.awakeFromNib()
self.placeholder = self.placeholder
}
}