【问题标题】:UITextField placeholder text attributes keeps resettingUITextField 占位符文本属性不断重置
【发布时间】:2015-12-21 11:57:52
【问题描述】:

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

    // 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)
        }
    }
}

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

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

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

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

【问题讨论】:

  • 有想过这个吗?我有同样的问题..

标签: ios swift uitextfield nsattributedstring


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2014-02-17
    • 2012-01-21
    相关资源
    最近更新 更多