好吧,我将尝试尽可能简单地分解这个问题。我在 ViewController 中有一个 tableView 。我有两个用于表格的原型(prototype)单元。我多次重复使用单元格来填充表格。
在其中一个单元格中,我向 label
添加了手势识别器,通过它我可以在标签位置显示 textField
并隐藏 标签
。现在,当我使用完 textField
并按回车键后,我希望标签文本更改为我在 textField
中输入的内容。所以我在viewController
中实现了UITextFieldDelegate
协议(protocol)。我还向单元格中的每个文本字段添加了标签,以便我知道 textField
返回的是什么以及该文本字段位于哪一行。
基本上,我想知道的是,如果我已经知道indexPath.row,是否有任何方法可以获取indexPath?
对于手势识别器,我可以通过从点击的位置获取索引路径来解决这个问题:
func genderTapped(sender: UITapGestureRecognizer) {
let tapLocation = sender.locationInView(self.profileInfoTable)
let indexPath = self.profileInfoTable.indexPathForRowAtPoint(tapLocation)
let cell = self.profileInfoTable.cellForRowAtIndexPath(indexPath!) as! editUserDataCell
cell.savedUserInput.hidden = true
cell.userDetailTextfield.becomeFirstResponder()
cell.userDetailTextfield.hidden = false
cell.userDetailTextfield.text = cell.savedUserInput.text!
}
我需要 indexPath
以便我可以引用单元格中包含的元素。任何人都可以提供任何见解吗?有人尝试过类似的方法吗?有什么方法可以仅使用行来访问单元格吗?
最佳答案
如果您能够在GestureMethod
中获取indexPath,那么您可以创建一个NSIndexPath
类型的实例属性,将其值存储在Gesture的方法中,然后使用indexPath在 textFieldShouldReturn
委托(delegate)方法中,类似这样。
var selectedIndexPath: NSIndexPath?
func genderTapped(sender: UITapGestureRecognizer) {
let tapLocation = sender.locationInView(self.profileInfoTable)
self.selectedIndexPath = self.profileInfoTable.indexPathForRowAtPoint(tapLocation)
let cell = self.profileInfoTable.cellForRowAtIndexPath(self.selectedIndexPath!) as! editUserDataCell
cell.savedUserInput.hidden = true
cell.userDetailTextfield.becomeFirstResponder()
cell.userDetailTextfield.hidden = false
cell.userDetailTextfield.text = cell.savedUserInput.text!
}
现在在 UITextFieldDelegate
方法中使用这个 self.selectedIndexPath
。
编辑:根据您的问题评论,您已经知道您只有一个 Section
,因此您也可以从该 创建
的 indexPath
textFieldtag
这样。
func textFieldShouldReturn(textField: UITextField) -> Bool {
let indexPath = NSIndexPath(forRow: textField.tag, inSection: 0)
//Or You can use self.selectedIndexPath also
}
关于ios - 如果您知道行,是否可以派生索引路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39121976/