ios - 删除 UITextField 中的最后一个字符

标签 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
    }

最佳答案

    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

}

关于ios - 删除 UITextField 中的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35863061/

相关文章:

objective-c - 如何在Objective C中将基于XML的字符串值转换为整数

ios - 为什么我的 UIView 加载不出来?

ios/swift - 我无法附加表格 View 单元格

ios - 蜂窝数据的可达性测试

iphone - 如何在 iPhone 上默认显示数字键盘?

ios - UILabel 和 UITextField 编辑字符

ios - UITextField 在执行字符限制的同时附加/在日期之间

ios - UITableView 删除按钮未出现并且也与我的标签重叠

ios - Calabash iOS - wait_for_element_exists 不起作用

swift - Metal 输出数组中的一项