ios - inset - uitextview
iPhone UITextField-изменить цвет текста заполнителя (20)
Я хотел бы изменить цвет текста заполнителя, который я установил в элементах UITextField
, чтобы сделать его черным.
Я бы предпочел сделать это, не используя обычный текст в качестве заполнителя, и должен переопределить все методы, чтобы имитировать поведение заполнителя.
Я считаю, что если я переопределю этот метод:
- (void)drawPlaceholderInRect:(CGRect)rect
то я должен это сделать. Но я не уверен, как получить доступ к фактическому объекту-заполнителю из этого метода.
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)
}
}
}
Версия 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)
}
}
}
Для iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Надеюсь, поможет.
Примечание. Apple может отклонить (0,01% шансов) ваше приложение, поскольку мы обращаемся к частному API. Я использую это во всех своих проектах с двух лет, но Apple не просила об этом.
Быстрая версия. Наверное, это помогло бы кому-то.
class TextField: UITextField {
override var placeholder: String? {
didSet {
let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
self.attributedPlaceholder = placeholderString
}
}
}
В Свифт:
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])
}
Вы можете изменить цвет текста Placeholder на любой цвет, который вы хотите, используя приведенный ниже код.
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
Вы можете переопределить drawPlaceholderInRect:(CGRect)rect
как таковой, чтобы вручную визуализировать текст заполнителя:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
Для разработчиков Xamarin.iOS я нашел это из этого документа https://developer.xamarin.com/api/type/Foundation.NSAttributedString/
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red });
Для тех, кто использует Monotouch (Xamarin.iOS), вот ответ Адама, переведенный на C #:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}
Другой вариант, который не требует подкласса - оставьте пробел и поместите надпись поверх кнопки редактирования. Управляйте ярлыком так же, как вы управляете заполнителем (очистка, когда пользователь вводит что-либо ..)
Категории 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
Лучшее, что я могу сделать для 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];
}
}
Мне нужно было поддерживать выравнивание заполнителя, поэтому ответа Адама было недостаточно для меня.
Чтобы решить эту проблему, я использовал небольшой вариант, который, я надеюсь, поможет некоторым из вас:
- (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];
}
Переопределение 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;
}
Почему бы вам просто не использовать метод UIAppearance
:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
Следующее только с iOS6 + (как указано в комментарии Александра W):
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];
Это решение для Swift 4.1
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
Я новый для xcode, и я нашел способ приблизиться к тому же эффекту.
Я разместил uilabel вместо владельца места с желаемым форматом и спрятал его в
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;
Я соглашаюсь на его работу, а не на реальное решение, но эффект был таким же, как и у этой link
ПРИМЕЧАНИЕ. Все еще работает на iOS 7: |
в быстрой версии 3.X
passwordTxtField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
В Swift 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
}
}