gpt4 book ai didi

ios - 如何从 tableview 单元格中检索文本字段值

转载 作者:可可西里 更新时间:2023-11-01 00:21:37 26 4
gpt4 key购买 nike

我有一个包含 2 个单元格的表格 View 。两个单元格都有一个文本字段和一个标签。文本字段采用用户名/电子邮件地址和密码的值。

var emailAddress: String?
var password: String?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! TextFieldCell

cell.label.text = loginOptions[indexPath.row]
cell.textField.placeholder = loginOptions[indexPath.row]

if indexPath.row == 0 {
emailAddress = cell.textField.text!
}
if indexPath.row == 1 {
password = cell.textField.text!
}

return cell
}

下面是一个函数,用于检查文本框中是否有任何文本,如果没有,则显示一个警告 Controller ,建议填写所有字段。

func signInButtonTapped() {

if emailAddress!.isEmpty || password!.isEmpty {

let alert = UIAlertController(title: "Alert", message: "all fields are required to be filled in", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}

}

如何从单元格中检索文本字段值以检查它们是否为空?上面的代码不起作用,因为文本字段总是返回空。虽然,希望可以看到我正在努力实现的目标

最佳答案

第一步

在当前类 UITextFieldDelegate 中添加委托(delegate)

class ViewController: UIViewController,UITextFieldDelegate  

第二步

在您的cellForRowAtIndexPath 上调用当前字段的委托(delegate)并添加标签

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! TextFieldCell

cell.label.text = loginOptions[indexPath.row]
cell.textField.placeholder = loginOptions[indexPath.row]
// add the following lines
cell.textField.delegate = self
cell.textField.tag = indexPath.row


return cell
}

第三步

调用 UITextField 委托(delegate)

 func textFieldDidEndEditing(textField: UITextField) {
print("TextField did end editing method called")

if !textField.text.isEmpty // check textfield contains value or not
{
if textField.tag == 0
{
emailAddress = textField.text!
}
else
{
password = textField.text!
}
}

func textFieldShouldReturn(textField: UITextField) -> Bool {

textField.resignFirstResponder();
return true;
}

func textFieldDidBeginEditing(textField: UITextField!) {
if textField.tag == 0
{
emailAddress = ""
}
else
{
password = ""
}
}

第四步

如果 emailAddress & password 不包含错误值,则调用你的函数

  func signInButtonTapped() {

if emailAddress!.isEmpty || password!.isEmpty {

let alert = UIAlertController(title: "Alert", message: "all fields are required to be filled in", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
// continue your work
}

}

关于ios - 如何从 tableview 单元格中检索文本字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38763158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com