UITextField右对齐时,会有以下问题:
1.第一个字符输入空格,光标会跳到左侧;
2.如果先输入其它字符,然后输入空格,此时输入的空格不会立即显示,直到再次输入其它字符时该空格会与输入的字符同时显示出来;
3.输入内容末尾是空格时,结束输入后,空格不展示,只在编辑的时候显示
解决方案1:
private lazy var contentTextField: UITextField = {
let textField = UITextField()
textField.font = UIFont.normalFont()
textField.textAlignment = .Right
textField.delegate = self
textField.addTarget(self, action: #selector(textChange(_:)), forControlEvents: .EditingChanged)
return textField
}()
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if range.location == textField.text?.length && string == " " {
textField.text = textField.text?.stringByAppendingString("\u{00a0}")
// 调用一次textChange(textField),解决拦截代理方法textField: shouldChangeCharactersInRange: replacementString:对于空格返回false时,不能监听UITextFieldTextDidChangeNotification的问题。
textChange(textField)
return false
}
return true
}
@objc private func textChange(textField : UITextField) {
guard let text = textField.text else {
return
}
// 使用时需要将空格替换回去
if let callBack = callBackOfTextFieldEndEditing {
let contentSpace = textField.text!.stringByReplacingOccurrencesOfString("\u{00a0}", withString: " ")
let content = contentSpace.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
callBack(text: content)
}
}
解决方案2:
private lazy var contentTextField: UITextField = {
let textField = UITextField()
textField.font = UIFont.normalFont()
textField.textAlignment = .Right
textField.addTarget(self, action: #selector(textChange(_:)), forControlEvents: .EditingChanged)
return textField
}()
@objc private func textChange(textField : UITextField) {
guard let text = textField.text else {
return
}
let range = textField.markedTextRange
if range != nil {
return
}
let textRange = textField.selectedTextRange
textField.text = text.stringByReplacingOccurrencesOfString(" ", withString: "\u{00a0}")
textField.selectedTextRange = textRange
// 使用时需要将空格替换回去
if let callBack = callBackOfTextFieldEndEditing {
let contentSpace = textField.text!.stringByReplacingOccurrencesOfString("\u{00a0}", withString: " ")
let content = contentSpace.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
callBack(text: content)
}
}