首页 > 解决方案 > 如何软化 TableView 中的开始和结束更新

问题描述

我在 TableView 中有三个单元格。它在第一个单元格上有一个按钮,当按下它时,第一个单元格的垂直大小会被扩展。

在视图控制器中:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 1 {
        return 0
    }
    else if indexPath.section == 0 {
        return CGFloat(expandedHeight) //700 //500
    }
    else if indexPath.section == 2 {
        return 240
    }
    return 133
} 
//I've modified some of my code, but it works this way.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.section == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "one", for: indexPath) as! one

        return cell
    }
    else if indexPath.section == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "two", for: indexPath) as! two

        return cell
    }
    else if indexPath.section == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "thr", for: indexPath) as! thr

        return cell
    }

    return UITableViewCell()
}

func ExpandedButtonClick(_ height: Int)
{
    tableView.beginUpdates()
    expandedHeight = height // 500 700 switch
    tableView.endUpdates()
}

在 TableViewCell(一个)中:

@IBAction func btnClickExpanded(_ sender: Any)
{
    if let myViewController = parentViewController as? ViewController
    {
        if constraintExpend.constant == 500
        {
            constraintExpend.constant = 700
            myViewController.ExpandedButtonClick(700)
        }
        else
        {
            constraintExpend.constant = 500
            myViewController.ExpandedButtonClick(500)
        }
    }
}

一切都很完美,但有一个问题。

只有我看到的屏幕部分应该是动画的,但整个屏幕都在移动。看到这一点令人不安。

如果我只想为扩展部分设置动画怎么办?

我想在固定屏幕的同时展开。

标签: iosswifttableview

解决方案


我很难找到它,因为问题有点不同。

总之,我找到了完美的答案。

具有动态单元格高度的 UITableView 的@Sujan Simha reloadData() 导致跳跃滚动

在我的问题中,ExpandedButtonClick 函数

func ExpandedButtonClick (_ height: Int)
{
    expandedHeight = height
    tableView.beginUpdates ()
    tableView.endUpdates ()
    tableView.layer.removeAllAnimations ()
    tableView.setContentOffset (tableView.contentOffset, animated: false)
}

这完美!


推荐阅读