如何获取带有动态单元格的UITableView中的多个textFields的值? [英] How to get the values of multiple textFields in UITableView with dynamic cells?

查看:54
本文介绍了如何获取带有动态单元格的UITableView中的多个textFields的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在UIViewController中,我有一个带有1个动态原型单元格的UITableView,该单元格的类类型为TextInputTableViewCell.
在原型单元的内容视图"中,我要添加一个textField.

In a UIViewController I have a UITableView with 1 Dynamic Prototype cell of class type TextInputTableViewCell.
In the Content View of the prototype cell I am adding a textField.

  1. 如何用userInfo中的数据填充文本字段?
  2. 一旦用户编辑了每个textField的数据,如何获取它们?

我已经阅读过我应该使用标签的信息,但是其他人则说这种方法容易出错和脆弱.无论如何,我不知道如何使用标签或其他方法从字段中获取数据.请指教.

I have read on SO that I should use tags, but others said that this method is prone to bugs and fragile. Anyway, I don't know how to get the data from the fields using tags or other method. Please advise.

import Foundation
import UIKit
import Firebase

 class TextInputTableViewCell: UITableViewCell, UITextFieldDelegate{ 
      @IBOutlet weak var textField: UITextField!

     //closure when the text changes
     var textChangedCallBack: ((_ cell: TextInputTableViewCell, _ text:String) -> ())?
      //Delegate method called when the text field loses focus
     func textFieldDidEndEditing(_ textField: UITextField) {
    textChangedCallBack?(self,textField.text!)
  }
}//end of class TextInputTableViewCell



class EditProfile: UIViewController, UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate {

 var dbRef:FIRDatabaseReference! //create a reference to Firebase
 var userInfo = [FireBaseData]() //this array will hold all data under userType in Firebase



@IBOutlet weak var tableView: UITableView!
@IBAction func saveToFirebase(_ sender: Any) {  

 //will post data from text fields  to firebase
}


struct Item {
    var name:String
    var editable:Bool
}

let placeHolderItems = [
    Item(name: "Name", editable: false),
    Item(name: "Phone Number", editable: true),
    Item(name: "Email", editable: true),
    Item(name: "Flat Number", editable: true),
    Item(name: "Street Address", editable: true),
    Item(name: "Postcode", editable: true)
]


override func viewDidLoad() {
    super.viewDidLoad()

   self.dbRef = FIRDatabase.database().reference().child("Cleaners")
    self.tableView.delegate = self
    self.tableView.dataSource = self
}

   override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(true)

   //get user's profile from firebase
    self.startObservingDB { (userProfile) in

        if userProfile.count > 0 {
            self.userInfo = userProfile
             self.tableView.reloadData()
        }
    }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return placeHolderItems.count
}



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextInputCell") as! TextInputTableViewCell

    cell.textField.isEnabled = placeHolderItems[indexPath.row].editable
    cell.textField.placeholder = placeHolderItems[indexPath.row].name

 //After viewWillAppear finishes, self.userInfo will have the profile of
 //the user. How can I get here each textField  of the tableView so I can
   //populate each one of them with data from  self.userInfo?



         if !self.userInfo.isEmpty{

switch indexPath.row{
    case 0:
         cell.textField.text = self.userInfo[0].FirstName + " " + self.userInfo[indexPath.row].LastName
    case 1:
        cell.textField.text = self.userInfo[0].PhoneNumber

    case 2: cell.textField.text = self.userInfo[0].EmailAddress

    case 3: cell.textField.text = self.userInfo[0].FlatNumber

    case 4: cell.textField.text = self.userInfo[0].StreetAddress

    case 5: cell.textField.text = self.userInfo[0].PostCode

    default:
        break
     }
 }


    cell.textChangedCallBack = {(cell, text) in

        //get the cell's current index path 
        if let path = tableView.indexPath(for: cell) {

            //get the item at that row
            var item = self.placeHolderItems[path.row]

            //update the item with the new name  
        }  
    }

    return cell
  }
 }//end of EditProfileclass





extension EditProfile {


  //get user's profile in order to populate it in tableView
   func startObservingDB(callback:@escaping ((_ snapShot: [FireBaseData]) -> Void)) {

    //check if user is singed in
    guard let uid = FIRAuth.auth()?.currentUser?.uid  else {
        return
    }  

    dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
        var profileData = [FireBaseData]()

        for keyVal in snapshot.children{

            let userData = FireBaseData(snapshot: keyVal as! FIRDataSnapshot)
            profileData.append(userData)
                       }
        callback(profileData)

    }, withCancel: { (Error:Any) in 
        print("error is \(Error as! String)")

    })
    dbRef.removeAllObservers()

}//end of startObserving

}//end of EditProfile Class


推荐答案

通常要解决的问题是:用户已经在表视图单元格中编辑了文本字段,现在我们要更新数据型号.但是哪个单元格包含此文本字段?

The usual problem to be solved is: The user has a edited a text field in a table view cell, and now we want to update the data model accordingly. But which cell contains this text field?

概念哪个"的真正含义是:包含单元格表示的索引路径是什么?如果知道这一点,就可以轻松地更新模型,因为如果正确设计了表视图数据源,那么我们已经知道如何通过索引路径访问模型.

The notion "which" really means: what is the index path represented by the containing cell? If we knew that, we could easily update the model, because if our table view data source is correctly designed, we already know how to access the model by means of the index path.

所以我要做的就是简单地将视图层次结构从文本字段移动到单元格,然后询问表视图此单元格代表什么索引路径.这是我的应用程序中常用的模式:

So what I do is simply walk up the view hierarchy from the text field to the cell, and then ask the table view what index path this cell represents. This is a commonly used pattern in my apps:

func textFieldDidEndEditing(_ textField: UITextField) {
    var v : UIView = textField
    repeat { v = v.superview! } while !(v is UITableViewCell)
    let cell = v as! MyCell // or UITableViewCell or whatever
    let ip = self.tableView.indexPath(for:cell)!
    // and now we have the index path! update the model
}

这篇关于如何获取带有动态单元格的UITableView中的多个textFields的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆