在表格单元格中选择隐藏元素 - Swift

时间:2016-01-05 00:47:05

标签: ios swift uitableview

我按照此应用程序构建了一个包含自定义单元格的表格:https://github.com/awseeley/Custom-Table-Cell

我正在尝试扩展单元格并在单击单元格时显示不同的内容。

以下是我在视图控制器中的内容:

var cellTapped:Bool = true
var currentRow = 0;

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //CODE TO BE RUN ON CELL TOUCH

    let selectedRowIndex = indexPath
    currentRow = selectedRowIndex.row

    let cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TblCell

    cell.image.hidden = true

    tableView.beginUpdates()
    tableView.endUpdates()

}



func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == currentRow {
        if cellTapped == false {
            cellTapped = true

            return 141
        } else {
            cellTapped = false
            return 70
        }
    }
    return 70
}

单击时单元格会展开,再次单击时单元格会缩小。但图像并没有隐藏。如何隐藏图像?有没有更好的方法在选择单元格时显示另一个自定义.xib文件并具有展开/折叠效果?

2 个答案:

答案 0 :(得分:1)

  1. 您应将以下工具添加到cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        if indexPath.row == currentRow {
            if cellTapped == false {
                cell.image.hidden = false
            } else {
                cell.image.hidden = true
            }
        }
    
        return cell
    }
    
  2. didSelectRowAtIndexPath你应该删除错误的代码:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //CODE TO BE RUN ON CELL TOUCH
    
        let selectedRowIndex = indexPath
        currentRow = selectedRowIndex.row
        tableView.reloadData()
    
    }
    
    1. 如果你想使用想要使用tableView.beginUpdate()来获得更好的动画,你可以参考我的演示:

      Demo hide image on cell

    2. 希望这有帮助!

答案 1 :(得分:-1)

我对它并不熟悉,但您可以查看Stack View。我认为它可以帮助你做你想做的事情:

http://www.raywenderlich.com/114552/uistackview-tutorial-introducing-stack-views