Reputation: 23
After spending time for debuging I recognized that UITextField adds whitespaces to my strings pasted from clip board.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var input: String
let newString = string.trimmingCharacters(in: .whitespacesAndNewlines) // newString = "123"
if let oldString = textField.text { // oldString = "456"
input = oldString
input.insert(contentsOf: newString, at: input.index(input.startIndex, offsetBy: range.location)) // rang.location = 2, input = "4 123 56" but it supposed to be "412356"
} else {
input = newString
}
return true
}
I have two questions:
1- Why it happens only by pasting at second and more times?
2- How can I avoid adding these whitespaces to my pasted strings?
Upvotes: 1
Views: 50
Reputation: 5073
You are probably observing the effects of the smartInsertDeleteType
property. You can change that like so:
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.smartInsertDeleteType = .no
}
}
Upvotes: 2