我正在玩动画。我已经设置了一个 tableView
和一个带有 UIView
的自定义 tableViewCell
。 UIView
宽度在 10 秒内从 400 变为 0。现在有了 tableView
的关键特性,当表格滚动时,单元格就会被渲染。这会做一些事情:
- 离开可见框架时动画的单元格;
UIView
消失了。 - 当滚动时,一些
UIView
在单元格变得可见时开始动画。
代码如下:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath) as! listTableViewCell
cell.testlabel.text = "\(indexPath.row)"
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let myCell = cell as? listTableViewCell {
UIView.animate(withDuration: 10, animations: {
myCell.timeRemainingView.frame.size.width = 0
self.loadViewIfNeeded()
})
}
}
问题:我希望所有单元格在应用程序启动时开始动画,并在我滚动时保持动画。
更新:
这是我所做的。我正在使用 CADisplayLink 并以这种方式运行动画。我在自定义 tableviewcell 文件中执行所有这些操作。我唯一需要弄清楚的是每个单元格的自定义持续时间。这是代码:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(timeRemainingView)
contentView.addSubview(testlabel)
contentView.bringSubviewToFront(testlabel)
contentView.backgroundColor = .white
let displayLink = CADisplayLink(target: self, selector: #selector(handleProgressAnimation))
displayLink.add(to: .main, forMode: .defaultRunLoopMode)
setupViews()
}
let animationDuration = 60.0
let animationStartDate = Date()
@objc func handleProgressAnimation() {
let currenttime = Date()
let elapsed = currenttime.timeIntervalSince(animationStartDate)
let percentage = elapsed / animationDuration
timeRemainingView.frame.size.width = CGFloat(400 - (400 * percentage))
}
有什么提示或建议吗?
最佳答案
像这样替换你的 cellForRowAtIndex:
let identifier = "homeCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! listTableViewCell
if cell == nil {
tableView.register(UINib(nibName: "listTableViewCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? listTableViewCell
}
cell.testlabel.text = "\(indexPath.row)"
return cell
关于ios - 滚动 tableview 时 UITableViewCells 内容动画变得乱七八糟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304059/