swift - 如何使用 swift 引用文本字段?

标签 swift xcode sqlite debugging field

我想使用 alert.textFields?.last?.textalert.textFields?.last?.text 函数引用两个以上的文本字段输入,但我不确定如何引用第一个和最后一个之间的字段。

    let alert = UIAlertController(title: "Insert Student", message: nil, preferredStyle: .alert)
    alert.addTextField{ (tf) in tf.placeholder = "Name" }
    alert.addTextField{ (tf) in tf.placeholder = "House" }
    alert.addTextField{ (tf) in tf.placeholder = "Score" }

    let action = UIAlertAction (title:"Submit", style: .default) { (_) in
        guard let name = alert.textFields?.first?.text,
        let house = alert.textFields?.last?.text,
            let score = alert.textFields?.last?.text

最佳答案

let alert = UIAlertController(title: "Insert Student", message: nil, preferredStyle: .alert)
    alert.addTextField{ (tf) in
        tf.placeholder = "Name"
        tf.tag = 11
    }
    alert.addTextField{ (tf) in
        tf.placeholder = "House"
        tf.tag = 12
    }
    alert.addTextField{ (tf) in
        tf.placeholder = "Score"
        tf.tag = 13
    }

    let action = UIAlertAction (title:"Submit", style: .default) { (_) in
        guard let nameTextField = alert.view.viewWithTag(11) as? UITextField,
            let houseTextField = alert.view.viewWithTag(12) as? UITextField,
            let scoreTextField = alert.view.viewWithTag(13) as? UITextField else { return }

        guard let name = nameTextField.text,
            let house = houseTextField.text,
            let score = scoreTextField.text else { return }
    }

关于swift - 如何使用 swift 引用文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55970454/

相关文章:

ios - 使用图表框架。 swift 2.0

xcode - 关闭模态视图 Swift

Xcode 中的 Python 语法高亮

xcode - 在 Swift 中发出 Amazon Web Services S3 POST 请求

iphone - 将 UISeachBar 与 SQLite3 结合使用

php - 尝试从 php 脚本获取 Json 数据时出错

ios - 升级到 Xcode 7 后 Ar 丢失

java - Android sqlite 插入数据 SQLiteException

c# - 通过 NHibernate 在不加载对象的情况下更新一对多关系

ios - Swift 函数/方法中的 "_"字符