【发布时间】:2012-02-25 12:58:29
【问题描述】:
只是作为背景,这个问题与我之前发布的这个问题有关:Trying to expand/collapse UITableViewCell from a UIButton on the custom cell
总而言之,我有一个带有几个自定义表格单元格的 UITableView。每个自定义 UITableViewCell 都有一个文本区域,后跟一个“查看更多”按钮。本质上,每个单元格最初会显示 3 行文本,但是当用户点击“查看更多”按钮时,单元格应该扩展到整个文本区域的高度。再次点击按钮将折叠单元格。
我觉得这很难形象化,所以我在这里拍了一个短视频:http://dl.dropbox.com/u/762437/cell-animation.mov
(大约是一个 3.5mb 的文件,所以加载时间不应该那么长)。在视频中,我展示了一个执行展开/折叠动画的单元格。展开时,“查看更多”按钮会向下动画。再次点击它时,它只是跳回到原来的位置,没有动画。 编辑:对不起,我应该更清楚。 UITableView 正确地为单元格设置动画,我要问的是如何使“查看更多”按钮正确地设置动画。
我已经让展开/折叠工作正常了(我做对了还是错了是另一回事!),但动画没有按我的预期工作。展开动画有效,但折叠无效。
在每个自定义 UITableViewCell 类中,我都有一个 IBAction,当用户点击“查看更多”按钮时会调用它。我还跟踪当前在 NSMutableArray 中扩展的单元格。当用户点击“关闭”按钮时,该单元格将从数组中移除。
在我的 tableView 的 cellForRowAtIndexPath 中,我检查数组以查看哪些单元格应展开,哪些应以默认大小显示。
我正在使用以下代码:
// Check if the array contains the particular cell, if so, then it needs to be expanded
if([expandedRows containsObject:indexPath])
{
// Expand the cell's text area to fit the entire contents
[cell.textLabel sizeToFitFixedWidth:cell.textLabel.frame.size.width];
// Find the new Y-position of where the "Close" button.
// The new Y position should be at the bottom of the newly expanded text label
CGFloat bottomYPos = cell.textLabel.frame.origin.y + cell.textLabel.frame.size.height;
// Get a rect with the "Close" button's frame and new Y position
CGRect buttonRect = cell.showAllButton.frame;
buttonRect.origin.y = bottomYPos;
// Animation block to shift the "Close" button down to its new rect
[UIView animateWithDuration:0.3
delay:0.0
options: UIViewAnimationCurveLinear
animations:^{
cell.showAllButton.frame = buttonRect;
[cell.showAllButton setTitle:@"Close" forState:UIControlStateNormal];
}
completion:^(BOOL finished){
NSLog(@"Done 1!");
}];
}
else
{
// This cell is currently collapsed
// Get the button rect and subtract the height delta to put it back
// OriginalCellSizes is where I keep track of the original Y positions
CGRect buttonRect = cell.showAllButton.frame;
buttonRect.origin.y -= cell.frame.size.height - [[originalCellSizes objectAtIndex:indexPath.row] floatValue];
// Animation block for the Button
[UIView animateWithDuration:0.3
delay:0.0
options: UIViewAnimationCurveEaseOut
animations:^{
cell.showAllButton.frame = buttonRect;
[cell.showAllButton setTitle:@"View More" forState:UIControlStateNormal];
}
completion:^(BOOL finished){
NSLog(@"Done! 2");
}];
}
经过调查,我发现在那个if-else的“else”分支中,buttonRect已经和原来的位置在同一个Y位置。我怀疑这就是为什么没有动画发生的原因,但我不确定。
任何帮助都会非常棒!
【问题讨论】:
标签: iphone uitableview uianimation