I am trying to remove the last character in the UITextField if the character count goes over 200. But it has no effect:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
print(textField.text?.characters.count)
if (textField.text?.characters.count > 200){
self.textField.shake()
self.textField.becomeFirstResponder()
self.textField.text?.characters.dropLast()
}
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool // return NO to not change text
{
let textFieldString = textField.text! as NSString;
var newString = textFieldString.stringByReplacingCharactersInRange(range, withString:string)
if newString.characters.count > 200 {
// This will remove just last character, If u want to remove all the characters starting from 201st character pass 200 to substringToIndex method
newString = newString.substringToIndex(newString.endIndex.advancedBy(-1))
textField.text = newString
return false
}
return true
}
You can remove the last element of the textField's text characters with any of the following methods:
let myString = "Hello!"
let result1 = myString.substringToIndex(myString.endIndex.advancedBy(-1)) // Hello
var anotherString = "World!"
let result2 = String.init(anotherString.characters.dropLast()) // World
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
print(newString.characters.count)
if newString.characters.count > 200{
self.textField.shake()
self.textField.becomeFirstResponder()
self.textField.text = String.init(newString.characters.dropLast())
//or self.textField.text = newString.substringToIndex(newString.endIndex.advancedBy(-1))
}
return true
}
Try this:
let string = self.textField.text?.characters.dropLast()
self.textField.text = String(string)
Add String extension
extension String {
func getSubString(from: Int, to: Int) -> String {
let startIndex = self.index(self.startIndex, offsetBy: from)
let endIndex = self.index(self.startIndex, offsetBy: to)
return String(self[startIndex..<endIndex])
}
}
Usage
if let text = exerciseAnswer.text, text.count > 0 {
exerciseAnswer.text = text.getSubString(from: 0, to: text.count - 1)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.