使用此UITextField子類,配置後綴,並享受
提高
class PostFixTextField: UITextField {
@IBInspectable var postfix : String = ""
@IBInspectable var removePostfixOnEditing : Bool = true
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.addTarget(self, action: #selector(textHasChanged), for: .editingDidEnd)
self.addTarget(self, action: #selector(removePostFix), for: .editingDidBegin)
self.addTarget(self, action: #selector(textHasChanged), for: .editingChanged)
}
func textHasChanged()
{
self.removePostFix()
self.addPostFix()
self.setCursorPosition(input: self, position: (self.originalText()?.characters.count)!)
}
private func setCursorPosition(input: UITextField, position: Int) {
let position = input.position(from: input.beginningOfDocument, offset: position)!
input.selectedTextRange = input.textRange(from: position, to: position)
}
func addPostFix()
{
if(self.text != nil)
{
self.text = self.text! + postfix
}
}
func originalText() ->String?{
let prefixRange = NSString(string: (self.attributedText?.string)!).range(of: postfix)
if(prefixRange.location != NSNotFound)
{
return self.text!.replacingOccurrences(of: postfix, with: "")
}
return self.text
}
func removePostFix(){
if(self.removePostfixOnEditing && self.text != nil)
{
self.text = self.originalText()
}
}
}
希望這有助於你
我的回答確實幫助你嗎? –