Ios UITextField占位符文本属性保持重置
UITextField占位符属性有问题。我将文本属性定义为一个全局变量,在viewDidLoad方法中设置UITextField的defaultTextAttributes和attributedPlaceholder,并实现文本字段的委托方法,以便在编辑结束后文本字段保留为空时显示默认文本Ios UITextField占位符文本属性保持重置,ios,swift,uitextfield,nsattributedstring,Ios,Swift,Uitextfield,Nsattributedstring,UITextField占位符属性有问题。我将文本属性定义为一个全局变量,在viewDidLoad方法中设置UITextField的defaultTextAttributes和attributedPlaceholder,并实现文本字段的委托方法,以便在编辑结束后文本字段保留为空时显示默认文本 // MARK: - Define global meme text attributes // Set text attributes let memeTextAttributes = [
// 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)
}
}
}
文本和占位符都应该具有相同的文本属性,但问题是如果用户在编辑文本字段后将其保留为空,则下次他们进行编辑时,文本仅为填充,并且没有在文本属性中定义的笔划。但是,如果用户没有将文本字段留空,那么文本将以应有的方式显示
如果初始编辑为空,则文本没有笔划:
如果初始编辑不是空的,则文本显示良好:
知道为什么会这样吗?如果在加载视图时设置了文本/占位符属性,那么它不应该更改,除非某些方法显式更改它,对吗 可以使用textFieldShouldEndEditing:而不是TextFielddEndediting:来避免这种行为。对你来说,这并不重要。你有没有想过?我也有同样的问题。。