ios - Swift:类型 'string' 的值没有成员 'length'

标签 ios string swift

<分区>

我在我的应用程序中实现了一些 TextField 功能,所以我使用了 TextField 委托(delegate),但它显示了一些错误,如“字符串类型的值没有成员长度”我不知道如何解决这个问题,请帮助我解决这个问题。

这里我给出了我正在尝试的代码。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    var oldLength: Int = textField.text!.characters.count
    var replacementLength: Int = string.characters.count
    var rangeLength: Int = range.length
    var newLength: Int = oldLength - rangeLength + replacementLength
    if textField.tag == 1 {
        if string.length > 0 && !NSScanner.scannerWithString(string).scanInt(nil) {  **------>//Error was showed in this line.**
            return false
        }
        // This 'tabs' to next field when entering digits
        if newLength == 5 {
            if textField == txtOtp4 {
                textField.resignFirstResponder()
            }
        }
        else if oldLength > 0 && newLength == 0 {

        }

        return newLength <= 4
    }
    else {
        if newLength == 11 {
            if textField == txtPhoneNumber {
                textField.resignFirstResponder()
            }
            return newLength <= 10
        }
    }
    return true
    // This allows numeric text only, but also backspace for deletes
}

最佳答案

替换

if string.length > 0

通过

if string.characters.count > 0

为 Swift 4 编辑:

String 现在符合 Collection 协议(protocol),所以它有一个 count 属性。

关于ios - Swift:类型 'string' 的值没有成员 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35623160/

相关文章:

ios - 向字典添加值不会持久化

string - 解释 "str - ' 0'"字符串转整数时的用法。

ios - UICollectionView Cell 的阴影在 cell 即将出屏时突然消失

ios - 仅当当前值大于存储值时才覆盖 Firebase DB 值

ios - 如何为 ios 制作类似 uber 的设计?

objective-c - UIManagedDocument 上的 saveToURL 核心数据失败

ios - Swift,从异步 block 返回值

MySQL 字符串中多次出现相同的字母

php - 在 PHP 中将 `null` 与字符串连接是否安全?

ios - 核心数据在线程中保存对象与关系