iPhone UITextField-자리 표시 자 텍스트 색상 변경


566

UITextField컨트롤에 설정 한 자리 표시 자 텍스트의 색상을 변경하여 검은 색으로 만들고 싶습니다 .

자리 표시 자로 일반 텍스트를 사용하지 않고 자리 표시 자의 동작을 모방하기 위해 모든 방법을 재정의하지 않고이 작업을 선호합니다.

이 방법을 재정의하면 믿습니다.

- (void)drawPlaceholderInRect:(CGRect)rect

그런 다음이 작업을 수행 할 수 있어야합니다. 그러나이 방법 내에서 실제 자리 표시 자 객체에 액세스하는 방법을 잘 모르겠습니다.

답변:


804

iOS 6의 UIView에 속성 문자열이 도입되었으므로 다음과 같이 플레이스 홀더 텍스트에 색상을 지정할 수 있습니다.

if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
  UIColor *color = [UIColor blackColor];
  textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
  NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
  // TODO: Add fall-back code to set placeholder color.
}

2
이것은 좋지만 이것이 작동하기 전에 IB에 자리 표시 자 값을 설정해야합니다.
— gheese

4
이 코드는 respondsToSelector 호출로 래핑 할 가치가 있습니다.이 코드가 없으면 6.0 이전 배포 대상 (인스턴스로 전송 된 인식 할 수없는 선택기)에서 충돌이 발생합니다.
— gheese

5
의 문서는 attributedPlaceholder색상을 제외한 텍스트 속성을 사용합니다.
— 매트 코놀리

1
NSFontAttributeName [[NSAttributedString alloc] initWithString:@"placeholder" attributes: @{NSForegroundColorAttributeName: color, NSFontAttributeName : font}];
— dev4u

3
iOS 7에서이 오류가 발생했습니다 :[<UITextField 0x11561d90> valueForUndefinedKey:]: this class is not key value coding-compliant for the key _field.
— i_am_jorf

237

쉽고 통증이 없으며 일부에게는 쉬운 대안이 될 수 있습니다.

_placeholderLabel.textColor

프로덕션 용으로 제안되지 않은 Apple은 제출을 거부 할 수 있습니다.


1
프로덕션에서 이것을 사용하고 있습니까? 나는 개인 재산에 접근하는 것을 의미합니다.
— Geri Borbás

11
빠른 복사 및 붙여 넣기를 위해 답변에 텍스트를 추가하십시오. _placeholderLabel.textColor
— Philiiiiiipp

47
이 방법을 사용하지 마십시오.이를 사용했으며 itune 상점에서 내 응용 프로그램을 거부했습니다.
— Asad ali

1
나는 어떤 종류의 개인 라이브러리 방법도 절대로 해결책으로 추천해서는 안된다고 생각합니다
— Skrew

2
@jungledev _placeholderLabel는 개인 재산입니다. 이 솔루션은 개인 API 사용으로 거부 될 수 있습니다.
— Sean Kladek

194

drawPlaceholderInRect:(CGRect)rect자리 표시 자 텍스트를 수동으로 렌더링하도록 재정의 할 수 있습니다 .

- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor blueColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}

44
같은 뭔가가 [self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];아마 더 좋다. 그렇게하면 textAlignment재산 을 존중하게 됩니다. SSTextField 클래스 에 이것을 추가했습니다 . 프로젝트에서 자유롭게 사용하십시오.
— Sam Soffes

52
Koteg의 말을 절대하지 마십시오. 카테고리를 통해 메소드를 대체하지 마십시오. EVER
— 조슈아 와인버그

8
@JoshuaWeinberg 당신의 sugestion 뒤에 특별한 이유가 있습니까?
— Krishnan

5
@Krishnan은 카테고리에서 중복 메소드를 구현하는 것이 지원되지 않으며 어떤 메소드가 호출되는지 또는 둘 다 호출되는지 또는 호출 순서를 확실하게 알 수 없습니다.
— sean woodward

8
iOS7에서는 텍스트를 세로로 가운데에 맞추기 위해 CGRectInset (rect, 0, (rect.size.height-self.font.lineHeight) / 2.0)을 사용하여 rect를 변경할 수 있습니다.
— Brian S

170

아래 코드를 사용하여 자리 표시 자 텍스트 색상을 원하는 색상으로 변경할 수 있습니다.

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

6
최고의 답변이 제안되었습니다. 작동하고 문서화 된 API를 사용합니다.
— Ian Hoar

2
UISearchBar에서 어떻게 작동합니까? trustedPlaceholder 속성이 없습니다.
— gilsaints88

1
이 답변은 올바르지 않습니다 - 워드 프로세서에 따르면, attributedPlaceholder의 텍스트 색상 정보는 무시됩니다 developer.apple.com/library/ios/documentation/UIKit/Reference/...
— 애들 소리 쳐

모두 감사합니다. 도움이 되었기를 바랍니다. Adlai Holler는 시도 형제를 줘! 이 답변은 이전 버전의 iOS에 대한 것입니다. 당신이 더 나은 답변을 가지고 있다면 우리는 제안에 열려 있습니다.
— 만주

ValuePlaceholder 속성이 없기 때문에 iOS8에서 작동하지 않습니다
— Ben Clayton

157

아마도 이런 식으로 시도하고 싶지만 Apple은 개인 ivar에 액세스하는 것에 대해 경고 할 수 있습니다

[self.myTextField setValue:[UIColor darkGrayColor] 
                forKeyPath:@"_placeholderLabel.textColor"];

참고
Martin Alléus에 따르면 iOS 7에서는 더 이상 작동하지 않습니다.


6
내 앱에서이 방법을 사용합니다. 리뷰는 괜찮 았습니다. 그래서 나는 그것을 사용하는 것이 좋다고 생각합니다.
— Michael A.

9
이 앱 스토어는 안전 하지 않으며 권장 해서는 안됩니다 . 이러한 기술을 사용하여 승인을 받거나 승인을 유지할 수는 없습니다.
— Sveinung Kval Bakken

31
승인 여부는 중요하지 않습니다. 중요한 것은 향후 OS 업데이트에서 앱이 중단 될 수 있다는 것입니다.
— pablasso

2
iOS 7에 아무런 문제가 없습니다 ... 노트에도 불구하고 시도해 보았지만 정상적으로 작동하는 것으로 보였으며 과거에는이 접근법을 아무런 문제없이 사용했습니다.
— WCByrne

6
이것은 항상 나쁜 생각이었고 이제는 iOS 13에서 깨졌습니다. Access to UITextField's _placeholderLabel ivar is prohibited. This is an application bug😈
— Ryder Mackay

154

이것은 스위프트 <3.0에서 작동합니다.

myTextField.attributedPlaceholder = 
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])

iOS 8.2 및 iOS 8.3 베타 4에서 테스트되었습니다.

스위프트 3 :

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])

스위프트 4 :

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

스위프트 4.2 :

myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

iOS8.2에서 솔루션을 사용하면 매력처럼 작동합니다. 완벽한 솔루션입니다. 목표 C에서도 사용.
— Akshit Zaveri 2019

73

스위프트에서 :

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}

스위프트 4.0에서 :

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}

전화하기 전에 자리 표시 자 텍스트를 설정하지 않으면 앱이 중단됩니다
— apinho

이것은 최고입니다, 감사합니다. @apinho 아무것도 여기에 충돌하지 않습니다
— Markus

// Swift 4에서 let placeholder = yourTextField.placeholder {yourTextField.attributedPlaceholder = NSAttributedString (string : placeholder, attributes : [NSAttributedStringKey.foregroundColor : UIColor.white])}
— Ronaldo Albertini

이 코드가 실행 된 후 자리 표시 자 텍스트 값을 변경하면 기본 자리 표시 자 색이 다시 나타납니다.
— Alessandro Vendruscolo

66

스위프트 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)
        }
    }
}

여기에 이미지 설명을 입력하십시오

스위프트 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)
        }
    }
}

스위프트 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)
        }
    }
}

컴파일러가를 찾을 수 없습니다 NSAttributedStringKey.
— Milan Kamilya

iOS 13에서 작동
— Jalil

43

다음은 iOS6 이상에서만 가능합니다 (Alexander W의 의견에 표시된대로).

UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
   [[NSAttributedString alloc]
       initWithString:@"Full Name"
       attributes:@{NSForegroundColorAttributeName:color}];

33

나는 이미이 문제에 직면했다. 제 경우에는 아래 코드가 정확합니다.

목표 C

[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

스위프트 4.X

tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")

iOS 13 스위프트 코드

tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])

iOS 13에 아래 코드를 사용할 수도 있습니다

let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red

희망이 도움이 될 수 있습니다.


@Ashu ios 13에서 충돌이 발생합니다. 'UITextField의 _placeholderLabel ivar에 액세스 할 수 없습니다. 이것은 응용 프로그램 버그입니다. 심지어 AppStore에 배치하는 것에 대해 이야기하고 있지 않은 빌드조차하지 않습니다
— Melany

1
IOS 13 이것은 제한되어 더 이상 이것을 사용할 수 없습니다
— Kishore Kumar

Objc 코드는 IOS 13에서 테스트되었으며 작동하지 않습니다.
— Mehdico

1
@Mehdico iOS 13에 대한 답변을 업데이트했습니다. 희망이 있습니다.
— Ashu

viewWillAppear또는 에서이 변경을 수행해야한다는 사실을 배우기에는 너무 오래 걸렸습니다 viewDidAppear. viewDidLoad너무 빠릅니다.
— 4

32

이를 통해 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"];

1
iOS13부터는 작동하지 않습니다
— Teddy

@ 테디 어떻게 지냈어? 나는 이것에 문제가 생기기 시작했다.
— Jalil

@Jalil 나는 아직도 당신을 위해 시간에 있기를 바랍니다. textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString : @ "text"속성 : @ {NSForegroundColorAttributeName : [UIColor colorWithHexString : @ "ffffff55"]}];
— Teddy

18

왜 UIAppearance메소드를 사용하지 않습니까?

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];

잘 작동합니다! 텍스트 색상은 영향을받지 않습니다 (적어도 textColor 속성에 다른 프록시 사용)
— HotJard

18

또한 한 줄의 코드없이 스토리 보드에서

여기에 이미지 설명을 입력하십시오


1
어떻게 알았어? 내가 생각하는 가장 좋은 방법이지만 어떻게 알 수 있습니까? iOS 프로그래밍에 익숙하지 않다고 알려주십시오.
— 야와 르

2
매우 보편적입니다. 일단 당신이 그것을 알고 어디서나 그것을 사용;)
— Petr Syrov

나는 그것의 뒤에 무엇이 실행되는지 이해하면 나는 그것을 많이 사용할 것임을 안다. 그러나 나는 "_placeholderLabel.textColor"를 의미하며 이것은 텍스트 필드의 자식 뷰 여야합니다. 컨트롤에 대한 이러한 유형의 정보를 볼 수있는 방법이 있습니까?
— 야와 르

2
@Yawar Xcode에서 뷰 계층 검사기를 사용하거나 디버거에서 뷰를 검사 할 수 있습니다.
— David Ganster

좋은 점은 텍스트 필드에 관계없이 키 패스에 동일한 '타일 / 이름'을 사용할 수 있습니다
— Naishta

16

스위프트 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])

12

iOS 6.0 이상

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

도움이 되길 바랍니다.

참고 : Apple이 비공개 API에 액세스 할 때 Apple이 앱을 거부 할 수 있습니다 (0.01 % 확률). 나는 2 년 이후 모든 프로젝트에서 이것을 사용하고 있지만 Apple은 이것을 요구하지 않았습니다.


terminating with uncaught exception of type NSExceptioniOS8 용
— Yar

10

Xamarin.iOS 개발자의 경우이 문서 https://developer.xamarin.com/api/type/Foundation.NSAttributedString/ 에서 찾았습니다.

textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor =  UIColor.Red });

감사합니다 !! UIStringAttributes가 아닌 CTStringAttributes를 처음 사용했으며 알아낼 수 없었습니다. 이것을 사용하지 않도록 조심하십시오 :new NSAttributedString("placeholderstring", new CTStringAttributes() { ForegroundColor = UIColor.Blue.CGColor });
— Yohan Dahmani

9

스위프트 버전. 아마 누군가를 도울 것입니다.

class TextField: UITextField {
   override var placeholder: String? {
        didSet {
            let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
            self.attributedPlaceholder = placeholderString
        }
    }
}

6

카테고리 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

6

iOS7에서 자리 표시 자의 색상뿐만 아니라 세로 및 가로 정렬을 모두 처리합니다. drawInRect 및 drawAtPoint는 더 이상 현재 컨텍스트 fillColor를 사용하지 않습니다.

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html

오브제 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

텍스트를 세로로 올바르게 가운데 맞추는 (사용자 정의 글꼴에 유용한)이 우수한 솔루션에 감사합니다. 내가 추가 할 수있는 유일한 방법은이 솔루션이 다시 하락하여 수정에 아이폰 OS 6 이상 (쉬운 정도와 호환되지 않는 것입니다 [: RECT withFont : self.font의 lineBreakMode을 : self.placeholder drawInRect NSLineBreakByTruncatingTail 정렬 : self.textAlignment]
— lifjoy

6

iOS 6 이상은에서 제공 attributedPlaceholder합니다 UITextField. iOS 3.2 이상은에서 제공 setAttributes:range:합니다 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;

무엇이 문제의 원인인지 잘 모르겠습니다.이 코드는 viewdidLoad에서 호출했습니다. 새로운 색과 글꼴 크기는 다시 그린 후에 만 ​​나타납니다. 이것과 함께 다른 일을해야합니까?
— Vinayaka Karjigi 5

자리 표시 자 텍스트에 해당 글꼴을 사용하기 전에 UITextfield에 글꼴을 설정하는 것을 잊었습니다. 내 나쁜
— Vinayaka Karjigi

6

Swift 4.1을위한이 솔루션

    textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])

4

재정의 drawPlaceholderInRect:는 올바른 방법이지만 API (또는 설명서)의 버그로 인해 작동하지 않습니다.

이 메소드는에서 호출되지 않습니다 UITextField.

호출되지 않은 UITextField의 drawTextInRect 도 참조하십시오.

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;
}

리뷰 친화적 인 솔루션 공유에 대해 어떻게 생각하십니까?
— adam

내가 사용한 솔루션을 추가했습니다. 이것은 얼마 전에 있었던 것처럼 약간의 파기를해야했습니다. :)
— henning77

나는 이것과 비슷한 것을했지만 코드를 카테고리에 배치하고 shouldChangeCharacters에서 코드를 표시할지 여부를 확인해야했습니다.이 카테고리의 두 번째 방법 인-(void) overlayPlaceholderVisible : (BOOL) visible ;
— David van Dugteren

3

나는 xcode를 처음 접했고 같은 효과를 얻는 방법을 찾았습니다.

원하는 형식의 자리 표시 자 대신 uilabel을 배치하고 숨 깁니다.

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    switch (textField.tag)
    {
        case 0:
            lblUserName.hidden=YES;
            break;

        case 1:
            lblPassword.hidden=YES;
            break;

        default:
            break;
    }
}

나는 그 해결책과 실제 해결책이 아니라는 것에 동의하지만 그 효과는이 링크 에서 얻었습니다.

참고 : 여전히 iOS 7에서 작동합니다 : |


3

주의 사항 5 스위프트.

let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString

String"DON'T_DELETE"가 있는 곳에 빈 문자열을 입력해야합니다. 해당 문자열이 다른 곳에 코드로 설정되어 있어도주의해야합니다. 5 분의 헤드 스크래칭을 줄일 수 있습니다.


2

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];
  }
}

2

Monotouch (Xamarin.iOS)를 사용하는 사람들을 위해 다음은 C #으로 번역 된 Adam의 답변입니다.

public class MyTextBox : UITextField
{
    public override void DrawPlaceholder(RectangleF rect)
    {
        UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
        new NSString(this.Placeholder).DrawString(rect, Font);
    }
}

큰. 이것은 분명하지 않았습니다. 아마도 시간을 절약 할 수 있습니다. :) 솔루션을 편집했지만 Font텍스트 필드 속성 에서 글꼴 세트를 사용하는 것이 더 좋습니다 .
— Wolfgang Schreurs

1

자리 표시 자 정렬을 유지해야 아담의 대답이 충분하지 않았습니다.

이 문제를 해결하기 위해 작은 변형을 사용하여 일부 사용자에게 도움이되기를 바랍니다.

- (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];
}

UILineBreakModeTailTruncationiOS 6
— Supertecnoboff

1
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];

이것에 대한 약간의 힌트는 당신이 개인 iVar (_placeholderLabel)에 접근하고 있으며 과거에는 Apple이 그 일을하는 데 약간의 어려움을 겪었다는 것입니다. :)
— Alexander W

1

다중 색상으로 속성이 지정된 텍스트 필드 자리 표시자를 설정하려면

Text를 지정하십시오.

  //txtServiceText is your Textfield
 _txtServiceText.placeholder=@"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;

출력 :-

여기에 이미지 설명을 입력하십시오


0

서브 클래 싱이 필요하지 않은 또 다른 옵션-자리 표시자를 비워두고 편집 ​​단추 위에 레이블을 붙입니다. 플레이스 홀더를 관리하는 것처럼 레이블을 관리하십시오 (사용자가 입력 한 내용을 지우면 ..)


하나의 텍스트 필드가 있으면 이것이 효과적 일 것이라고 생각하지만보다 세계적인 규모 로이 변경을 시도하면이 솔루션이 프로젝트에 상당한 오버 헤드를 추가합니다.
— James Parker
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.