将触摸事件处理到一个 Table Cell

Handling touch events to one UITableCell

我有一些 UITableViewCells,我可以在其中执行点击操作。

当单击操作开始时,单元格将展开并显示 UIPickerView、UITextView 或其他数据。 (参见示例图片)

当您再次单击 TableCell 时,单元格将折叠并显示原始状态。

目前,当我通过展开操作单击 UITableViewCell 时,每个单元格都会展开。当我点击一个单元格时,我希望所有其他单元格都折叠起来,只展开被点击的单元格。

问题:

如何为已展开的 table 单元格提供一种接收所有触摸事件的状态。 (成为全屏第一响应者)先关闭,关闭后发送点击事件给对应的UITableViewCell

我已将 UITextView 设置为第一响应者,它会在弹出后关闭键盘,但我希望 table 单元格成为点击事件的处理程序。

示例代码

func togglePicker() {
    //This function is called when the UITableCell is clicked.

    canBecomeFirstResponder()

    // Some code here which adds UIPickerView, UITextView or other data.

    setNeedsLayout()
}

我试过这个代码,但是这个单元格只接收在这个单元格中触发的触摸事件,而不是在它的边界之外。

示例图片

Orginal cell state

First cell is expanded

好的,通过查看您正在更改单元格框架的图像,您在问题中提出的 When I click on a cell I want every other cell to be collapsed and only expand the clicked one. 的一种解决方案,您可以存储单击的单元格的索引路径并使用此折叠其他单元格,如果显示该单元格的选择器视图,例如

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if showIndexPath?.row == indexPath.row 
    {
        return 330 //expanded height for example
    }
    else {
         return 100 //normal state height for example
    }
}

 //in this method u can decide which one to expand or collapse 
 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    //if user selected the same cell again close it
    if showIndexPath?.row == indexPath.row 
    {
        //already expanded, collapse it 
        showIndexPath = nil
        tableView .reloadRowsAtIndexPaths([showIndexPath!], withRowAnimation: .Fade)

    }
    else
    {
        //expand this cell's index path 
        showIndexPath = indexPath
        tableView .reloadRowsAtIndexPaths([showIndexPath!], withRowAnimation: .Fade)
    }
}

我实施了以下解决方案:

class CustomCell: UITableViewCell {

   var delegate: CustomCellDelegate?
   var focussed: Bool = false

   function becomeFocussed() {
      //Put some code here to change the design
      setNeedsLayout()
      focussed = true
      delegate?.isFocussed(self)
   }

   function becomeNormaleState() {
      //Put some code here to change the design to the original state.
      focussed = false
      setNeedsLayout()
   }

}

每个Cell都有两个函数:becomeFocussed()和becomeNormaleState()。单击单元格时,应调用函数 becomeFocussed()。 此函数告诉代表该单元格已被选中。

在 TableViewController 中,函数 isFocussed(cell : UITableViewCell) 循环遍历当前 tableView 的所有单元格,然后为每个聚焦的单元格调用 "becomeNormaleState()"。