【问题标题】:Animation with constraints in UITableViewCell launches incorrectlyUITableViewCell 中带有约束的动画启动不正确
【发布时间】:2016-01-20 05:13:07
【问题描述】:

我遇到了一个问题,我通过调整自动布局约束来为表格单元格中简单 UIView 的大小设置动画。

当我第一次启动表时,一切都坏了。

如果我重新加载表格,它会很好地工作。

它是一个只有几行代码的单一视图控制器。请下载此demo project 以查看它的实际应用。

这是我在整个 UIViewController 中的代码:

import UIKit

class TableCell: UITableViewCell {
    @IBOutlet weak var constraintRedBarWidth: NSLayoutConstraint!
    @IBOutlet weak var labelTitle: UILabel!
    @IBOutlet weak var viewBarArea: UIView!
    @IBOutlet weak var viewRedBar: UIView!
}

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    var tableData : [CGFloat] = [1, 0.90, 0.70, 0.80,0.50] //percentages

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func btnReloadTable(sender: AnyObject) {
        tableView.reloadData()
    }

}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TableCell") as! TableCell
        cell.labelTitle.text = "Item \(indexPath.row + 1)"
        cell.constraintRedBarWidth.constant = 1
        cell.layoutIfNeeded()
        cell.constraintRedBarWidth.constant = cell.viewBarArea.frame.width * tableData[indexPath.row]
        UIView.animateWithDuration(0.5, animations: {
            cell.layoutIfNeeded()
        })
        return cell
    }

}

viewBarArea 只是红色视图的父视图,简单地表示栏的可能最大尺寸。

【问题讨论】:

  • 问题是cell.viewBarArea.frame.width 给出了单元格的原始宽度......就像你使用 wAnyhAny 并且你的单元格宽度是 580,而不是第一次给出 580 的宽度......你必须使用 @987654328 @ 以根据设备获取更新的宽度
  • 所以在 viewWIllLayoutSubviews 中,我应该循环遍历可见的表格单元格并应用动画吗?这可能有效,但似乎有点密集。我去看看
  • @El Captain,我刚刚意识到这是行不通的,因为动画会在滚动或执行其他任何操作时不断重复。

标签: ios swift uitableview autolayout


【解决方案1】:

使用这一行 cellForRowAtIndexPath 就是这样

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 2019-08-30
  • 2019-07-28
相关资源
最近更新 更多