归因于UITextField的文本

4 uitextfield ios swift

我正在尝试使用UITextField的属性文本.我已经定制了我的占位符文本,但它忽略了我为主文本属性设置的值.

nameTextField.attributedText = NSAttributedString(string: "", attributes: [NSForegroundColorAttributeName : UIColor.white, NSParagraphStyleAttributeName : paraStyle, NSFontAttributeName : UIFont.init(name: "HelveticaNeue-Bold", size: 16)]);
Run Code Online (Sandbox Code Playgroud)

奇怪的是,故事板中也存在一个问题.如果我在文本字段上设置值,则在我单击后立即丢失它们.

以前有人经历过吗?

Don*_*Mag 5

您想要设置typingAttributes,而不是referencedString.

试试这个:

func textFieldDidBeginEditing(_ textField: UITextField) {

    let paraStyle: NSParagraphStyle = NSParagraphStyle()
    textField.typingAttributes = [NSForegroundColorAttributeName : UIColor.white, NSParagraphStyleAttributeName : paraStyle, NSFontAttributeName : UIFont.init(name: "HelveticaNeue-Bold", size: 16)]

}
Run Code Online (Sandbox Code Playgroud)


Tun*_*Fam 5

解决方案

textField.defaultTextAttributes = yourAttributes // call in viewDidLoad
Run Code Online (Sandbox Code Playgroud)

@DonMag 的解决方案有效,但会导致内存使用问题,并且应用程序开始滞后(很多)。因此typingAttributes,在使用 时,内存使用量在某个时间点上升并且从未停止,并导致应用程序冻结。