删除UITextField中的最后一个字符

时间:2016-03-08 09:03:33

标签: ios swift uitextfield

如果字符数超过200,我试图删除UITextField中的最后一个字符。但它没有效果:

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
    }

4 个答案:

答案 0 :(得分:2)

    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

}

答案 1 :(得分:1)

您可以使用以下任何一种方法删除textField文本字符的最后一个元素:

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
}

答案 2 :(得分:0)

添加字符串扩展

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])
   }
}

用法

if let text = exerciseAnswer.text, text.count > 0 {
    exerciseAnswer.text = text.getSubString(from: 0, to: text.count - 1)
}

答案 3 :(得分:-1)

试试这个:

let string = self.textField.text?.characters.dropLast()
self.textField.text = String(string)