Program Club

UITextField 자리 표시 자 색상 변경

proclub 2020. 10. 22. 23:43
반응형

UITextField 자리 표시 자 색상 변경


의 자리 표시 자 색상을 동적으로 변경하는 방법 UITextField? 이것은 항상 동일한 시스템 색상입니다.

xib 편집기에는 옵션이 없습니다.


문서에서

@property (nonatomic, copy) NSAttributedString * attributedPlaceholder

이 속성은 기본적으로 nil입니다. 설정된 경우 자리 표시 자 문자열은 70 % 회색 색상과 속성 문자열의 나머지 스타일 정보 (텍스트 색상 제외)를 사용하여 그려집니다. 이 속성에 새 값을 할당하면 서식 정보가 없더라도 자리 표시 자 속성의 값이 동일한 문자열 데이터로 바뀝니다. 이 속성에 새 값을 할당해도 텍스트 필드의 다른 스타일 관련 속성에는 영향을주지 않습니다.

목표 -C

NSAttributedString *str = [[NSAttributedString alloc] initWithString:@"Some Text" attributes:@{ NSForegroundColorAttributeName : [UIColor redColor] }];
self.myTextField.attributedPlaceholder = str;

빠른

let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
myTextField.attributedPlaceholder = str

스위프트 4

let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
myTextField.attributedPlaceholder = str

쉽고 완벽한 솔루션.

_placeholderLabel.textColor

신속하게

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

목표 -C

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

PS는 Stackoverflow에서 3 가지 답변을 복사했습니다.


아래 코드 사용

[YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];

먼저이 확장 추가

extension UITextField{
    @IBInspectable var placeHolderTextColor: UIColor? {
        set {
            let placeholderText = self.placeholder != nil ? self.placeholder! : ""
            attributedPlaceholder = NSAttributedString(string:placeholderText, attributes:[NSForegroundColorAttributeName: newValue!])
        }
        get{
            return self.placeHolderTextColor
        }
    }
}

그런 다음 스토리 보드를 통해 또는 다음과 같이 설정하여 자리 표시 자 텍스트 색상을 변경할 수 있습니다.

textfield.placeHolderTextColor = UIColor.red

나는 이것을 SWIFT에서 사용합니다.

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

이것은 다른 사람들에게도 효과가있는 것 같습니다. 왜 이전에 저에게 효과가 없었는지 모르겠습니다 ... 어쩌면 일부 프로젝트 설정일 수도 있습니다. 의견 주셔서 감사합니다. 현재는 다시 테스트 할 방법이 없습니다.

구식 : 텍스트가 올바르게 적용되는 이유를 모르겠지만 자리 표시 자 색상은 그대로 유지됩니다 (검정 / 회색).

--iOS8


이 시도:

NSAttributedString *strUser = [[NSAttributedString alloc] initWithString:@"Username" attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
NSAttributedString *strPassword = [[NSAttributedString alloc] initWithString:@"Password" attributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];

self.username.attributedPlaceholder = strUser;
self.password.attributedPlaceholder = strPassword;

다음 코드를 사용할 수 있습니다.

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

이 솔루션은 서브 클래 싱 및 개인 ivar없이 작동합니다.

@IBOutlet weak var emailTextField: UITextField! {
    didSet {
        if emailTextField != nil {
            let placeholderText = NSLocalizedString("Tap here to enter", comment: "Tap here to enter")
            let placeholderString = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor(white: 0.66, alpha: 1.0)])
            emailTextField.attributedPlaceholder = placeholderString
        }
    }
}

이 시도.

UIColor *color = [UIColor redColor];
self.txtUsername.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Placeholder Text" attributes:@{NSForegroundColorAttributeName:color}];

Swift에서 @DogCoffee의 대답은 다음과 같습니다.

let placeholderAttrs = [ NSForegroundColorAttributeName : UIColor.redColor()]
let placeholder = NSAttributedString(string: "Some text", attributes: placeholderAttrs)

textField.attributedPlaceholder = placeholder

이것은 위의 @Medin Piranej가 제공 한 확장 버전의 개선 된 버전입니다 (좋은 생각입니다!). 이 버전은 placeHolderTextColor를 가져 오려고하면 끝없는 순환을 피하고 색상 세트가 nil 인 경우 충돌을 방지합니다.

public extension UITextField {

@IBInspectable public var placeholderColor: UIColor? {
    get {
        if let attributedPlaceholder = attributedPlaceholder, attributedPlaceholder.length > 0 {
            var attributes = attributedPlaceholder.attributes(at: 0,
                                                              longestEffectiveRange: nil,
                                                              in: NSRange(location: 0, length: attributedPlaceholder.length))
            return attributes[NSForegroundColorAttributeName] as? UIColor
        }
        return nil
    }
    set {
        if let placeholderColor = newValue {
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "",
                                                       attributes:[NSForegroundColorAttributeName: placeholderColor])
        } else {
            // The placeholder string is drawn using a system-defined color.
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "")
        }
    }
}

}


신속한 3의 경우 UITextfield의 자리 표시 자 텍스트 색상을 변경하는 데이 코드를 사용할 수 있습니다.

 let placeholderColor = UIColor.red
 mytextField.attributedPlaceholder = NSAttributedString(string: mytextField.placeholder, attributes: [NSForegroundColorAttributeName : placeholderColor])

스위프트 4

let placeholderColor = UIColor.red
self.passwordTextField?.attributedPlaceholder = 
NSAttributedString(string:"placeholderText", attributes: 
[NSAttributedStringKey.foregroundColor : placeholderColor])

[yourtextFieldName setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];

참고 URL : https://stackoverflow.com/questions/21074417/change-of-uitextfield-placeholder-color

반응형