简体   繁体   English

使用Swift检查在tableview单元格中为文本字段选择的行?

[英]Check row selected for textfield in tableview cell using Swift?

I am trying to create a table view where the user can edit the textfield on each cell. 我试图创建一个表视图,用户可以在其中编辑每个单元格上的文本字段。 Each cell also allow the transition to another detail view controller. 每个单元还允许过渡到另一个详细信息视图控制器。 When the user tap on the cell's textfield, it should allow editing and storing the input text to an array respectively. 当用户点击单元格的文本字段时,它应允许编辑输入文本并将其分别存储到数组中。

The problem is that, how do I check the cell/row selected when the textfield is tapped using Swift? 问题是,当使用Swift轻敲文本字段时,如何检查选定的单元格/行? (I am able to check the cell being tapped, but not for the case of the textfield in the cell.) (我可以检查正在点击的单元格,但不能检查单元格中文本字段的情况。)

There's a couple ways to do this. 有两种方法可以做到这一点。

The superview property of your text field will be your UITableViewCell (unless you have it embedded within another view in the middle). 文本字段superview属性将是UITableViewCell(除非您将其嵌入在中间的另一个视图中)。

In my own code, I often subclass UITableViewCell (and sometimes even the controls within the cell) to give it a property which indicates which row number we're working with. 在我自己的代码中,我经常将UITableViewCell(有时甚至是单元格中的控件)子类化,为它提供一个属性,该属性指示我们正在处理的行号。

Each textField has a tag property which can be accessed using textField.tag . 每个textField都有一个tag属性,可以使用textField.tag进行访问。 If you are using a custom Cell, then under cellForRowAt indexPath add a line of code that assigns a tag to your textfield. 如果您使用的是自定义单元格,则在cellForRowAt indexPath添加一行代码,为您的文本字段分配标签。

let cell = tableView.dequeueReusableCell(withIdentifier: "<identifier>", for: indexPath) as? <customTableViewCell>
cell?.textField.tag = indexPath.row
//perform other cell operations

Make your TableViewController a UITextFieldDelegate, and under textFieldDidEndEditing access the tag property to know which textField was edited 使您的TableViewController成为UITextFieldDelegate,并在textFieldDidEndEditing下访问tag属性,以了解编辑了哪个textField

func textFieldDidEndEditing(_ textField: UITextField) {
        print("textfield tag \(textField.tag)")       
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM