使用Swift 4,iOS 11.1,Xcode 9.1,
从tableView做一个segue,我试着找出如何检测用户触摸的两个TextFields(在我的自定义单元格中)中的哪一个。我的custom-Cell tableView有两个TextField,如下图所示:
到目前为止,这是我的代码:
// tableView delegation-method:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
self.performSegue(withIdentifier: "goToMyNextVC", sender: cell)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToMyNextVC" {
let newVC = segue.destination as! MyNextViewController
let indexPath = self.tableView.indexPathForSelectedRow
print(indexPath?.row) // !!!!!! The cell-row is correct
let cell = sender as! MyCustomTableViewCell
newVC.someTextProperty1 = cell.firstTextFiled.text! // works well
newVC.someTextProperty2 = cell.secondTextFiled.text! // works well
// !!!! BUT HOW DO I GET WHICH OF THE TWO TEXTFIELDS WAS TOUCHED ?????????
// newVC.someTextProperty3 = ??????? text of touched TextField ???????
}
}
任何帮助赞赏!
您应该在MyCustomTableViewCell类的textField中注册tap事件,然后将哪个textField分配回viewController。
但更简单的解决方案是将两个不同的单元格用于两个不同的文本字段。
我找到了一个解决方案(以某种方式由Demosthese提示触发):
1.)在自定义单元格内部:调用单元格配置方法(分配每个textField的标签(或者我的情况下现在的标签......)
func configureCell(tag: Int) {
// assign tag (later used to expand / collapse the right cell)
self.fristTextField.tag = 1
self.secondTextField.tag = 2
self.firstTextField.isUserInteractionEnabled = true
self.secondTextField.isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let touch: UITouch = touches.first!
if (touch.view?.tag == self.firstTextField.tag) {
self.tagNrTouched = 1
} else if (touch.view?.tag == self.secondTextField.tag) {
self.tagNrTouched = 2
}
}