从自定义uitableview单元格中获取uitextfield数据 - Swift

时间:2017-07-31 08:31:33

标签: ios iphone swift uitableview uitextfield

我的自定义tableview单元格有一个带文本字段的问题。所以,我有一个单独的类用于带有文本字段的单元格,但我无法在tableview类中检索数据。 tableview类和textFieldShouldReturn函数中有textfield的委托,但是当我按下“完成”按钮时没有任何反应。哪里可以成问题?

非常感谢!

以下是表格视图的代码:

class MainTVC: UITableViewController, UITextFieldDelegate{

    var tableParts: [Dictionary<String, Any>] = []

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        tableParts = [
            ["type": "title", "data": "Some data", "enabled": true],
            ["type": "date", "data": "Some data", "enabled": true],
            ["type": "location", "data": "Loading...", "enabled": true],
        ]
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableParts[indexPath.row]
        switch(cell["type"] as! String) {
        ...
        case "textbox":
            let rTemplateTextBox = tableView.dequeueReusableCell(withIdentifier: "recapTextCell", for: indexPath) as! RTextCell
            rTemplateTextBox.textField.text = cell["data"] as? String ?? "No text"

            rTemplateTextBox.data = cell
            return rTemplateTextBox
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "defCell", for: indexPath)
            cell.textLabel?.text = "Unknown type of cell!"
            return cell
        }

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print("Should return!")
        return true
    }
}

对于一个单元格:

class RTextCell: UITableViewCell, UITextFieldDelegate {

    var textField = UITextField()
    var data: Dictionary<String, Any>?

    override func awakeFromNib() {
        super.awakeFromNib()

        textField.delegate = self

        let padding = UIView(frame: CGRect(x:0, y:0, width: 15, height: self.frame.height))

        textField = UITextField(frame: CGRect(x:0, y:0, width: self.frame.width, height: 40))
        textField.placeholder = "Your text here"
        textField.textColor = UIColor.white
        textField.tintColor = UIColor.white
        textField.backgroundColor = UIColor.clear
        textField.leftView = padding
        textField.leftViewMode = .always

        self.addSubview(textField)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print("Should return")
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if data != nil {
            data!["data"] = textField.text
            print("DATA: \(data!)")
        } else {
            print("No data")
        }
    }
}

2 个答案:

答案 0 :(得分:1)

第一个问题 - 在你的手机课上,awakeFromNib()你有:

// CREATE a UITextField
var textField = UITextField()
var data: Dictionary<String, Any>?

override func awakeFromNib() {
    super.awakeFromNib()

    // assign self as the delegate of textField
    textField.delegate = self

    let padding = UIView(frame: CGRect(x:0, y:0, width: 15, height: self.frame.height))

    // CREATE a NEW UITextField
    textField = UITextField(frame: CGRect(x:0, y:0, width: self.frame.width, height: 40))

因此,当您创建NEW textField时,它不再具有分配给它的委托。这就是为什么没有触发textFieldShouldReturntextFieldDidEndEditing的原因。

UITextField(frame: ..)行替换为:

    textField.frame = CGRect(x:0, y:0, width: self.frame.width, height: 40)

接下来,不要传入“数据对象”然后尝试操作,而是考虑使用回调闭包。

将您的手机类更改为:

class RTextCell: UITableViewCell, UITextFieldDelegate {

    var textField = UITextField()

    // this will be our "call back" closure
    var didEndEditAction : ((String)->())?

    override func awakeFromNib() {
        super.awakeFromNib()

        textField.delegate = self

        let padding = UIView(frame: CGRect(x:0, y:0, width: 15, height: self.frame.height))

        // just set the frame, don't create a NEW textField
        textField.frame = CGRect(x:0, y:0, width: self.frame.width, height: 40)
        textField.placeholder = "Your text here"
        textField.textColor = UIColor.white
        textField.tintColor = UIColor.white
        textField.backgroundColor = UIColor.clear
        textField.leftView = padding
        textField.leftViewMode = .always

        self.addSubview(textField)

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print("Should return")
        return true
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // call back using a closure
        didEndEditAction?(textField.text ?? "")
    }

}

然后像这样配置:

    case "textbox":
        let rTemplateTextBox = tableView.dequeueReusableCell(withIdentifier: "recapTextCell", for: indexPath) as! RTextCell
        rTemplateTextBox.textField.text = cell["data"] as? String ?? "No text"

        // setup the "call back" closure
        rTemplateTextBox.didEndEditAction = {
            (newText) in
            let cell = self.myData[indexPath.row]
            cell["data"] = newText
        }

        return rTemplateTextBox

答案 1 :(得分:0)

您可以在声明textField的任何地方获取单元tableView数据,只需使用以下代码

let indexPath = IndexPath(row: yourRow, section: yourSection)
let cell:InputDataCell = yourTable.cellForRow(at: indexPath) as! InputDataCell

if (cell.yourTextFieald.text?.characters.count)! {
    print(cell.yourTextFieald.text!)                           
}