动画UITableView节标题的自定义视图

时间:2013-05-15 15:04:51

标签: iphone ios objective-c uitableview

在我的应用中,我在场景中有UITableView动态更改宽度。当宽度改变时,我为场景的扩展设置动画 - 包括UITableView

UITableView包含带有自定义视图的部分标题,其中包含UILabel,它固定在视图的右侧。

当场景的宽度发生变化时,我会像这样调整表格的大小:

[UIView animateWithDuration:0.22
                      delay:0.02
                    options:UIViewAnimationOptionCurveLinear
                 animations:^
 {
     //Change width to 320 from 220
     [menuTable setFrame:CGRectMake(menuTable.frame.origin.x, menuTable.frame.origin.y, 320, menuTable.frame.size.height)];
 }
                 completion:^(BOOL finished)
 {

 }];

这样可以平滑地调整表格的大小,但是标题内的标签弹出到最终目的地 - 它没有动画。

我试过调用reloadData - 这具有相同的效果,没有动画。我尝试拨打beginUpdatesendUpdates,但没有效果。

我还应该尝试什么?

1 个答案:

答案 0 :(得分:1)

在我的标签扩展实验中,我发现Ryan Poolos在他的评论中所说的是真的 - 即使标签随着动画扩展,文本也会跳到新的位置(我用文本做了这个)设置为居中对齐)。

所以,我发现有效的唯一方法是使用计时器,如下所示:

-(IBAction)expandLabel:(id)sender {

    [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(expand:) userInfo:nil repeats:YES];
}

-(void)expand:(NSTimer *) aTimer {
    self.widthCon.constant += 1;
    if (self.widthCon.constant >= 200) [aTimer invalidate];
}

widthCon是我放在标签上的宽度约束的IBOutlet。如果您正在使用自动布局,则应通过更改约束来执行任何动画,而不是更改框架。我没有在节标题中尝试使用标签,但我认为如果使用此方法为表的宽度设置动画,它将起作用,并且标签的约束以这样的方式设置,即它遵循表的扩展。

编辑后:

经过更多实验,看起来计时器方法是使其移动标签(而不是扩展标签)的唯一方法。在这种情况下,宽度约束将是表视图本身。

第二次修改后:

更多实验。我发现问题是调用layoutSubviews(你不应该直接调用)而不是layoutIfNeeded。因此,您可以在没有计时器的情况下使标签位置设置为动画。这是我用来制作标题的代码,并按下按钮进行扩展:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *view = [[UITableViewHeaderFooterView alloc] init];
    view.tintColor = [UIColor yellowColor];
    UILabel *label = [[UILabel alloc] init];
    [label setTranslatesAutoresizingMaskIntoConstraints:NO];
    label.backgroundColor = [UIColor redColor];
    label.text = @"Test";
    [view.contentView addSubview:label];
    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[label]-|" options:0 metrics:nil views:@{@"label":label}]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    return view;
}

-(IBAction)expandTable:(id)sender {
    self.widthCon.constant = 300;
    [UIView animateWithDuration:1 animations:^{
        [self.view layoutIfNeeded];
    }];
}
相关问题