【发布时间】:2017-10-23 03:05:27
【问题描述】:
我在某些应用程序中看到,当您进入带有表格视图的屏幕时,单元格开始滑动的简短动画,显示红色的“滑动删除”按钮(UIContextualAction 按钮),然后它恢复正常。它给用户提示:“这些行可以滑动。”
有没有办法达到这个效果?也许是一种以编程方式启动行滑动然后取消它的方法?
【问题讨论】:
我在某些应用程序中看到,当您进入带有表格视图的屏幕时,单元格开始滑动的简短动画,显示红色的“滑动删除”按钮(UIContextualAction 按钮),然后它恢复正常。它给用户提示:“这些行可以滑动。”
有没有办法达到这个效果?也许是一种以编程方式启动行滑动然后取消它的方法?
【问题讨论】:
嗯,大约 1.5 年后,我终于想出了一个解决方案。
func animateSwipeHint() {
slideInFromRight()
}
private func slideInFromRight() {
UIView.animate(withDuration: 0.5, delay: 0.3, options: [.curveEaseOut], animations: {
self.cellBackgroundView.transform = CGAffineTransform(translationX: -self.swipeHintDistance, y: 0)
self.cellBackgroundView.layer.cornerRadius = 10
}) { (success) in
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
self.cellBackgroundView.transform = .identity
}, completion: { (success) in
// Slide from left if you have leading swipe actions
self.slideInFromLeft()
})
}
}
private func slideInFromLeft() {
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseOut], animations: {
self.cellBackgroundView.transform = CGAffineTransform(translationX: self.swipeHintDistance, y: 0)
}) { (success) in
UIView.animate(withDuration: 0.2, delay: 0, options: [.curveLinear], animations: {
self.cellBackgroundView.transform = .identity
})
}
}
在具有表格视图的视图控制器的viewDidLoad 中,我有以下代码:
if self.tableView.visibleCells.count > 0 {
let cell = self.tableView.visibleCells[0] as! TableViewCell
cell.animateSwipeHint()
}
如果您想更深入地了解此解决方案,我制作了一个视频: https://youtu.be/oAGoFd_GrxE
【讨论】:
我有一段很久以前看过的代码来为视图设置动画。因为我们的UITableViewCell 也是一个视图,我们可以使用它:) 你只需要让你的可见单元格动画,就像这样:
if let visibleCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? CustomCell {
print("Started animation...")
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = 0.6
animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0 ]
visibleCell.layer.add(animation, forKey: "shake")
}
如果这有帮助,请告诉我。测试过了。
编辑:
动画你的UITableView 让用户看到他们可以在单元格上滑动非常简单,试试这样:
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.tableView.setEditing(true, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) {
self.tableView.setEditing(false, animated: true)
}
}
但是,如果您想以编程方式滑动您的单元格以显示您的自定义行操作(我已经研究了一个小时),据我所知,您只能通过使用方法 swizzling 来实现这一点。看到这个答案:http://codejaxy.com/q/186524/ios-swift-uitableview-how-to-present-uitableviewrowactions-from-pressing-a-button
【讨论】: