You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UIAlertController多文本字段取值疑问:如何获取中间文本框内容?

解决UIAlertController多文本字段取值错误与Firebase文档ID设置问题

你当前的代码存在两个核心问题:

  1. 三个文本字段的取值逻辑错误,仅用.first和.last导致地址、电话号码的取值重复,且未正确获取中间的地址字段
  2. 错误地将姓名作为Firebase文档的documentID,既不符合唯一性要求,也浪费了Firebase自动生成唯一ID的能力

修正方案

1. 正确获取三个文本字段的值

UIAlertController的textFields是按添加顺序排列的数组,你添加的顺序是姓名→地址→电话号码,所以可以通过数组索引[0]、[1]、[2]分别获取对应字段的值。

2. 合理设置Firebase文档ID

Firebase的addDocument方法会自动生成一个全局唯一的文档ID,推荐直接使用这个自动生成的ID作为Employee的documentID,无需手动指定(避免重复或无意义的ID)。

修正后的完整代码

let composeAlert = UIAlertController(title: "Add Employee", message: "Add Employee", preferredStyle: .alert)

// 添加姓名输入框
composeAlert.addTextField { textField in
    textField.placeholder = "Name"
}

// 添加地址输入框
composeAlert.addTextField { textField in
    textField.placeholder = "Address" // 修正拼写错误:Adress → Address
}

// 添加电话号码输入框
composeAlert.addTextField { textField in
    textField.placeholder = "Phone Number"
}

// 添加取消按钮
composeAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

// 添加确认按钮
composeAlert.addAction(UIAlertAction(title: "Add Employee", style: .default, handler: { [weak self] action in
    guard let self = self else { return }
    // 按索引获取三个输入框的值,同时做非空校验
    guard let textFields = composeAlert.textFields,
          let name = textFields[0].text?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty,
          let address = textFields[1].text?.trimmingCharacters(in: .whitespacesAndNewlines), !address.isEmpty,
          let phoneNumber = textFields[2].text?.trimmingCharacters(in: .whitespacesAndNewlines), !phoneNumber.isEmpty else {
        // 可在此处提示用户输入不能为空
        return
    }
    
    // 先创建Employee对象(documentID暂时留空,后续用Firebase返回的ID填充)
    var newEmployee = Employee(name: name, adress: address, phoneNumber: phoneNumber, documentID: "", timeStamp: Date())
    
    // 上传到Firebase
    let ref = self.db.collection("employee").addDocument(data: newEmployee.dictionary) { error in
        if let error = error {
            print("Error adding document: \(error.localizedDescription)")
        } else {
            // 获取Firebase自动生成的文档ID,更新Employee对象
            newEmployee.documentID = ref.documentID
            // 此处可将newEmployee添加到TableView的数据源数组
            // 示例:self.employees.append(newEmployee)
            // 刷新TableView:self.tableView.reloadData()
            
            self.loadData()
            self.checkForUpdates()
            print("Document added with ID: \(ref.documentID)")
        }
    }
}))

self.present(composeAlert, animated: true, completion: nil)

关键修改说明

  • 文本字段取值:改用textFields[0]、textFields[1]、textFields[2]分别获取姓名、地址、电话号码,同时增加空字符串和空白字符校验,避免无效数据上传
  • DocumentID设置:移除从文本框获取documentID的错误逻辑,改用FirebaseaddDocument返回的ref.documentID作为Employee的documentID,保证ID唯一性
  • 内存安全:在handler中使用[weak self]避免循环引用
  • 拼写修正:将Adress修正为正确的Address

可选:手动生成DocumentID的方式

如果需要在上传前就确定文档ID,可以使用UUID手动生成,再用setDocument上传:

// 手动生成唯一ID
let documentID = UUID().uuidString
let newEmployee = Employee(name: name, adress: address, phoneNumber: phoneNumber, documentID: documentID, timeStamp: Date())

self.db.collection("employee").document(documentID).setData(newEmployee.dictionary) { error in
    // 处理回调逻辑
}

内容的提问来源于stack exchange,提问作者user21240940

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:45:31