Изменение цвета текста заполнителя с помощью Swift
у меня есть дизайн, который реализует темно-синий UITextField, поскольку текст заполнителя по умолчанию темно-серый цвет, я едва могу разобрать, что говорит текст держателя места.
я погуглил проблему, конечно, но я еще не придумал решение при использовании языка Swift, а не Obj-c.
есть ли способ изменить цвет текста заполнителя в UITextField с помощью Swift?
18 ответов:
вы можете установить текст заполнителя с помощью приписанной строки. Передайте цвет, который вы хотите с
attributes:var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30)) myTextField.backgroundColor = .blue myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.yellow])для Swift 3 + используйте следующее:
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
вы можете сделать это быстро, без добавления строки кода, используя Interface Builder.
выберите
UITextFieldи откройте инспектор идентификации справа:нажмите на кнопку Плюс и добавьте новый атрибут времени выполнения:
placeholderLabel.textColor (Swift 4)
_placeholderLabel.textColor (Swift 3 или меньше)
использовать цвета как тип и выберите цвет.
вот и все, вы не увидите результат, пока вы не запустите снова свое приложение.
создать
UITextFieldрасширение вот так:extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!]) } } }и в вашей раскадровке или .xib. Вы увидите
этот код работает в Swift3:
yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")дайте мне знать если вы имеете любой вопрос.
В Swift 3.0, Используйте
let color = UIColor.lightText textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])
чтобы установить цвет заполнителя один раз для всех
UITextFieldв вашем приложении, вы можете сделать:UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()это установит нужный цвет для всех
TextFieldзаполнители во всем приложении. Но он доступен только с iOS 9.там нет appearenceWhenContainedIn....() метод перед iOS 9 в swift, но вы можете использовать одно из решений, представленных здесь appearanceWhenContainedIn в Swift
Xcode 9.2 Swift 4
extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!]) } } }
для Swift 3 и 3.1 это отлично работает:
passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])
Swift 3 (вероятно, 2), Вы можете переопределить didSet на заполнителе в
UITextFieldподкласс, чтобы применить атрибут, таким образом:override var placeholder: String? { didSet { guard let tmpText = placeholder else { self.attributedPlaceholder = NSAttributedString(string: "") return } let textRange = NSMakeRange(0, tmpText.characters.count) let attributedText = NSMutableAttributedString(string: tmpText) attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange) self.attributedPlaceholder = attributedText } }
вот моя быстрая реализация для swift 4:
extension UITextField { func placeholderColor(_ color: UIColor){ var placeholderText = "" if self.placeholder != nil{ placeholderText = self.placeholder! } self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor : color]) } }Как использовать:
streetTextField?.placeholderColor(AppColor.blueColor)надеюсь, что это поможет кому-то!
Быстро
Создать Расширение UITextField
extension UITextField{ func setPlaceHolderColor(){ self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white]) } }
на Swift 4.0, X-code 9.1 версии или iOS 11 вы можете использовать следующий синтаксис, чтобы иметь другой цвет заполнителя
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
Быстро
func setPlaceholderColor(textField: UITextField, placeholderText: String) { textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack]) }Вы можете использовать это:
self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")
обновление ответа crubio для Swift 4
выберите поле UITextField и откройте инспектор идентификации справа:
нажмите на кнопку Плюс и добавьте новый атрибут времени выполнения:placeholderLabel.textColor (вместо _placeholderLabel.textColor)
используйте цвет как тип и выберите цвет.
Если вы запустите свой проект, вы увидите изменения.
Для Swift 4
txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
это больше о персонализации вашего текстового поля, но в любом случае я поделюсь этим кодом, полученным с другой страницы, и сделал его немного лучше:
import UIKit extension UITextField { func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) { self.borderStyle = UITextBorderStyle.none self.backgroundColor = UIColor.clear let borderLine = UIView() let height = 1.0 borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height) self.textColor = fontColor borderLine.backgroundColor = borderColor self.addSubview(borderLine) self.attributedPlaceholder = NSAttributedString( string: placeHolder, attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor] ) } }и вы можете использовать его как это:
self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)зная, что у вас есть
UITextFieldподключен кViewController.Источник: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/
используйте это для добавления атрибутивного заполнителя:
let attributes : [String : Any] = [ NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName : UIFont(name: "Helvetica Neue Light Italic", size: 12.0)! ] x_textfield.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)
yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])


Comments