UITableViewCell 的 setSelected 方法中的 animateWithDuration 没有效果

animateWithDuration in UITableViewCell's setSelected method has no effect

我正在为 UITableViewCell 的 selection/deselection 尝试一个简单的动画,如下所示:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        tabConstraint.constant = selected ? 40 : 20;

    } completion:nil];
}

将调用动画块中的代码,但它不是动画。一切正常,但根本没有任何动画。我怎样才能使单元格选择动画化?

每次更新自动布局约束时,都必须调用 layoutIfNeeded,

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {


    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        tabConstraint.constant = selected ? 40 : 20;
        [self layoutIfNeeded];

    } completion:nil];
}

您需要在 animations 块中调用 layoutIfNeeded。查看关于此问题的已接受答案以了解更多详细信息:How do I animate constraint changes?

您需要在动画块中调用 layoutIfNeeded():-)

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    tabConstraint.constant = selected ? 40 : 20;
    [UIView animateWithDuration: 0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        whateverTabYouHaveHere.layoutIfNeeded()
    } completion:nil];
}