TablviewCell在用户触摸时的高度变化

问题描述 投票:0回答:1

使用Swift 4,iOS 11.1,Xcode 9.1,

我想实现一个tableView-cell的动态高度变化。问题如下:我的tableView中的每个单元格都包含一个UIView(称为MyCellView)。在用户触摸单元格时,触摸单元格的MyCellView将改变其高度!

我成功实现了一个UIGestureRecognizer,它给我带来了动作。在动作方法中,我改变了触摸细胞的高度(到目前为止一直很好)。视图实际上改变了它的高度。

但不幸的是,如果MyCellView的新高度大于原始单元格高度,那么MyCellView会被剪掉!

如何在tableView中动态实现单个单元格的单元格高度更改?

这是我的手势识别器动作代码:

@objc func toWebviewTouch(_ sender : UITapGestureRecognizer) {

    self.MyCellView.frame = CGRect(x: self.MyCellView.frame.origin.x, 
                                   y: self.MyCellView.frame.origin.y,
                               width: self.MyCellView.frame.width,
                              height: self.myNewHeight)

    self.contentView.bringSubview(toFront: self.MyCellView)

    self.contentView.setNeedsLayout()
    self.setNeedsUpdateConstraints()
    self.updateConstraintsIfNeeded()
}

我也遵循了这个link的想法。但这似乎只会在tableView填充时更改tableView单元格的高度(而不是一旦tableView建立并且用户触摸单元格)。

任何帮助赞赏!

uiview tableview cell uigesturerecognizer swift4
1个回答
0
投票

哦,我找到了解决方案:

在这个link的帮助下,我实现了我的目标!

关键是在'didSelectRowAt'中使用以下内容

tableView.beginUpdates()
tableView.endUpdates()

之后,我需要从自定义单元格内部创建通知(即,当用户触摸单元格时,自定义单元格的gestureRecognizer触发本地通知(将单元格标记为Nr作为传递的消息) - 再次,使tableView.updates()

请参阅我的代码最底部的通知方法 - 摘录....

这是我的代码(摘录):

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // fixed to three to test...
    return 3
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = fromToTableView.dequeueReusableCell(withIdentifier: "FromToCell") as? FromToCustomTableViewCell

    cell?.configureCell(tag: indexPath.row)
    return cell!
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if self.cellIsSelected == indexPath {
        return 450
    }
    return 144
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    self.cellIsSelected = self.cellIsSelected == indexPath ? nil : indexPath
    tableView.beginUpdates()
    tableView.endUpdates()
}

// MARK: Notifications methods

@objc func expandCellHeightFromNotification(_ notification: NSNotification) {
    if let tag = notification.userInfo?["tag"] as? Int {
        self.cellIsSelected = IndexPath(item: tag, section: 0)
    }
    self.fromToTableView.beginUpdates()
    self.fromToTableView.endUpdates()
}

@objc func collapseCellHeightFromNotification(_ notification: NSNotification) {
    self.cellIsSelected = nil
    self.fromToTableView.beginUpdates()
    self.fromToTableView.endUpdates()
}
© www.soinside.com 2019 - 2024. All rights reserved.