UITextField占位符文本属性不断重置

时间:2015-09-24 01:17:41

标签: ios swift uitextfield nsattributedstring

我遇到了UITextField占位符属性的问题。我将文本属性定义为全局变量,在viewDidLoad方法中设置UITextField的defaultTextAttributes和attributionPlaceholder,并实现文本字段的委托方法,如果文本字段在编辑后保留为空,则显示默认文本结束。

    // MARK: - Define global meme text attributes
// Set text attributes
let memeTextAttributes = [
    NSStrokeColorAttributeName: UIColor.blackColor(),
    NSForegroundColorAttributeName: UIColor.whiteColor(),
    NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
    NSStrokeWidthAttributeName: -3.0
]

    override func viewDidLoad() {
    super.viewDidLoad()

    // Format image to maintain aspect ratio
    imagePickerView.contentMode = UIViewContentMode.ScaleAspectFit

    // Set text attributes and alignment
    topTextField.defaultTextAttributes = memeTextAttributes
    bottomTextField.defaultTextAttributes = memeTextAttributes
    topTextField.textAlignment = NSTextAlignment.Center
    bottomTextField.textAlignment = NSTextAlignment.Center

    // Set placeholder text for text fields
    topTextField.attributedPlaceholder = NSAttributedString(string: "TOP", attributes: memeTextAttributes)
    bottomTextField.attributedPlaceholder = NSAttributedString(string: "BOTTOM", attributes: memeTextAttributes)

    // Set text field delegates
    topTextField.delegate = self
    bottomTextField.delegate = self

    // Add tap gestures to dismiss keyboard when user taps outside of text field
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    view.addGestureRecognizer(tap)
}

文本字段委托方法:

    // MARK: - Text field delegate methods
func textFieldDidBeginEditing(textField: UITextField) {
    textField.attributedPlaceholder = nil
}

func textFieldDidEndEditing(textField: UITextField) {
    // If textField is empty, show respective default placeholder text
    if textField.text == "" {
        if textField == topTextField {
            textField.attributedPlaceholder = NSAttributedString(string: "TOP", attributes: memeTextAttributes)
        }
        else {
            textField.attributedPlaceholder = NSAttributedString(string: "BOTTOM", attributes: memeTextAttributes)
        }
    }
}

文本和占位符都应该具有相同的文本属性,但问题是如果用户在编辑后将文本字段留空,则下次编辑时文本仅填充且不会; t具有在文本属性中定义的笔划。但是,如果用户没有将文本字段留空,则文本显示应该的方式。

如果初始编辑为空,则文字没有笔画:http://i59.tinypic.com/200r1mp.png

如果初始编辑不为空,则文字显示正常:http://i57.tinypic.com/t8oqkm.png

知道为什么会这样吗?如果在加载视图时设置了文本/占位符属性,那么除非某些方法明确地更改它,否则它不应该更改?

1 个答案:

答案 0 :(得分:0)

您可以使用textFieldShouldEndEditing:代替textFieldDidEndEditing:来避免此行为。在你的情况下,这并不重要。