在Swift中逐行淡入UITableViewCell

Cla*_*nce 8 animation uitableview ios swift

我是swift的新手,我正在尝试使用UITableView,并且将逐个动画显示单元格.我怎样才能做到这一点?此外,如果新出现的单元格行不在屏幕上(隐藏在表格下方).每个单元格出现时如何移动表格?

    var tableData1: [String] = ["1", "2", "3", "4", "5", "6", "7"]

     override func viewWillAppear(animated: Bool) {
           tableView.scrollEnabled=false
    tableView.alpha=0.0
            NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "animateTable", userInfo: nil, repeats: false)
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData1.count
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell     {

        let cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
        cell.lblCarName.textAlignment = NSTextAlignment.Justified;
return cell
}

func animateTable() {

//what should be the code?//
}
Run Code Online (Sandbox Code Playgroud)

Kem*_*nak 12

步骤1

cellForRowAtIndexPath初始化单元格的方法中,将其隐藏起来;

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell     {
    let cell: TblCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TblCell
    cell.continueLabel.textAlignment = .justified
    cell.contentView.alpha = 0
    return cell
}
Run Code Online (Sandbox Code Playgroud)

第2步

让我们制作淡出动画.UITableViewDelegatewillDisplayCell一种方法能够检测到当你滚动到顶部或底部时,第一个单元格将显示在窗口上.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    UIView.animate(withDuration: 0.8, animations: {
        cell.contentView.alpha = 1
    })   
}
Run Code Online (Sandbox Code Playgroud)

您的淡入淡出动画正在进行中.最重要的是你无法在运行时直接设置单元格的alpha,因为iOS正在对单元格进行一些特殊的内部处理,UITableView而忽略了你的设置.所以,如果你设置你的细胞contentView,一切都会没事的.


Pie*_*epe 4

在 UITableView 中,当行进入您的“视野范围”时,它们会自动为您准备好。我假设您(至少最初不能)能够滚动 tableView,因此我们将以编程方式滚动它,使行随其移动而显示。我们怎么样?实际上 UITableView 有一个方法可以让我们将其滚动到特定行:

scrollToRowAtIndexPath(indexPath : NSIndexPath, atScrollPosition : UITableViewScrollPosition, animated : Bool);
Run Code Online (Sandbox Code Playgroud)

我太累了,写不了代码,所以我会尝试解释一下。首先,对于每个单元格,一旦它们被加载(cellForRowAtIndexPath),您就将 alpha 设置为 0。然后假设我们的屏幕适合前 5 行。您将按顺序对它们的 alpha 进行动画处理(使用 UIView.animateWithDuration ),直到第五个(索引 4),然后您将使用 5、然后 6 传递 NSIndexPath 来滚动到滚动到行属性索引路径(scrollToRowAtIndexPath),然后使用 6,...直到其余的(使用 scrollPosition = .底部)。对于它们中的每一个,您都会在它们加载后立即制作动画。请记住在这些互动之间留出一些时间。(第一个动画,运行 NSTimer 到第二个,然后继续)。当然,布尔动画应该是真的。