如何animationUITableView标题视图
我需要animation插入一个tableview标题视图。 我希望表格的行向下滑动,而标题视图展开其框架。
到目前为止,我得到的最好的结果是通过使用下面的代码:
[self.tableView beginUpdates]; [self.tableView setTableHeaderView:self.someHeaderView]; [self.tableView endUpdates];
这个解决scheme的问题是头本身没有得到animation,它的框架不能展开。
所以我得到的效果是表格行向下滑动(我想),但标题视图立即显示,我希望它扩大它的框架与animation。
有任何想法吗?
谢谢。
在CGRectZero
具有标题框架并使用animation设置其框架
[self.tableView beginUpdates]; [self.tableView setTableHeaderView:self.someHeaderView]; [UIView animateWithDuration:.5f animations:^{ CGRect theFrame = someBigger.frame; someHeaderView.frame = theFrame; }]; [self.tableView endUpdates];
下面是我在Swift中的工作,初始框架高度为零,并在animation闭包中将其更新到最大高度:
// Calculate new frame size for the table header var newRect = tableView.tableHeaderView?.frame newRect?.size.height = 42 // Get the reference to the header view let tblHeaderView = self.tableView.tableHeaderView // Animate the height change UIView.animateWithDuration(0.6, animations: { () -> Void in tblHeaderView?.frame = newRect! self.tableView.tableHeaderView = tblHeaderView })
选定的答案不适合我。 必须做到以下几点:
[UIView animateWithDuration: 0.5f animations: ^{ CGRect frame = self.tableView.tableHeaderView.frame; frame.size.height = self.headerViewController.preferredHeight; self.tableView.tableHeaderView.frame = frame; self.tableView.tableHeaderView = self.tableView.tableHeaderView; }];
真正特别的部分是,它在一个视图中工作,但不在同一视图控制器/视图层次结构的子类中。
我发现了在tableHeaderView
上实现真正的animation的最终和正确的方法!
•首先,如果您在Autolayout
,保持Margin
系统在您的标题视图。 使用Xcode 8现在可以(最后!),只是不要设置任何约束的头部子视图。 你将不得不设置正确的利润想法。
然后使用beginUpdates
和endUpdates
,但是把endUpdate
放到animation块中。
// [self.tableView setTableHeaderView:headerView]; // not needed if already there [self.tableView beginUpdates]; CGRect headerFrame = self.tableView.tableHeaderView.bounds; headerFrame.size.height = PLAccountHeaderErrorHeight; [UIView animateWithDuration:0.2 animations:^{ self.tableView.tableHeaderView.bounds = headerFrame; [self.tableView endUpdates]; }];
注:我只尝试iOS10,我会发布更新,当我的iOS9模拟器将被下载。
编辑
不幸的是,它不适用于iOS9以及iOS10:头本身不会改变它的高度,但头部子视图似乎移动,就像头部边界改变了一样。
使用下面的代码这个工程
extension UITableView { func hideTableHeaderView() -> Void { self.beginUpdates() UIView.animate(withDuration: 0.2, animations: { self.tableHeaderView = nil }) self.endUpdates() } func showTableHeaderView(header: UIView) -> Void { let headerView = header self.beginUpdates() let headerFrame = headerView.frame headerView.frame = CGRect() self.tableHeaderView = headerView UIView.animate(withDuration: 0.2, animations: { self.tableHeaderView?.frame = headerFrame self.tableHeaderView?.alpha = 0 self.endUpdates() }, completion: { (ok) in self.tableHeaderView?.alpha = 1 }) } }