我不相信占位符的默认行为是可编辑的,但是您可以使用NSAttributedString 模拟占位符值来完成您想要完成的工作。
我确信这可以进行优化,但在这里我创建了一个处理程序类,它充当给定UITextField 的委托,操纵用户输入的字符串以达到预期的效果。您使用所需的占位符字符串初始化处理程序,因此您可以使任何文本字段以这种方式工作。
import UIKit
class CustomPlaceholderTextFieldHandler: NSObject {
let placeholderText: String
let placeholderAttributes = [NSForegroundColorAttributeName : UIColor.lightGray]
let inputAttributes = [NSForegroundColorAttributeName : UIColor(red: 255/255, green: 153/255, blue: 0, alpha: 1.0)]
var input = ""
init(placeholder: String) {
self.placeholderText = placeholder
super.init()
}
func resetPlaceholder(for textField: UITextField) {
input = ""
setCombinedText(for: textField)
}
fileprivate func setCursorPosition(for textField: UITextField) {
guard let cursorPosition = textField.position(from: textField.beginningOfDocument, offset: input.characters.count)
else { return }
textField.selectedTextRange = textField.textRange(from: cursorPosition, to: cursorPosition)
}
fileprivate func setCombinedText(for textField: UITextField) {
let placeholderSubstring = placeholderText.substring(from: input.endIndex)
let attributedString = NSMutableAttributedString(string: input + placeholderSubstring, attributes: placeholderAttributes)
attributedString.addAttributes(inputAttributes, range: NSMakeRange(0, input.characters.count))
textField.attributedText = attributedString
}
}
extension CustomPlaceholderTextFieldHandler: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "" {
if input.characters.count > 0 {
input = input.substring(to: input.index(before: input.endIndex))
}
} else {
input += string
}
if input.characters.count <= placeholderText.characters.count {
setCombinedText(for: textField)
setCursorPosition(for: textField)
return false
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
setCursorPosition(for: textField)
}
}
这是我初始化上述 gif 的一种方式:
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
let placeholderHandler = CustomPlaceholderTextFieldHandler(placeholder: "_2_-__-__A")
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = placeholderHandler
placeholderHandler.resetPlaceholder(for: textField)
}
}
这可以扩展为在初始化时采用颜色参数、字体等,或者您可能会发现它更干净地继承UITextField 并使其成为自己的委托。我还没有真正测试过这个选择/删除/替换多个字符。
input 变量将返回用户在任何给定点输入的文本。此外,使用固定宽度的字体可以消除用户键入时的抖动并替换占位符文本。