如何为UIButton内容对齐中的更改设置动画

时间:2014-07-21 17:26:36

标签: ios objective-c cocoa-touch

UIButton的几个属性本身并不具有动画效果。其中一个属性是contentHorizontalAlignment属性。在没有运气的情况下搜索SO后,我想出了下面的答案来解决“不可动画”的问题。

2 个答案:

答案 0 :(得分:5)

您应该在更改对齐值后为layoutIfNeeded设置动画:

目标C:

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[UIView animateWithDuration:0.3 animations:^{       
  [self.view layoutIfNeeded];
}];

<强> Swift3:

button.contentHorizontalAlignment = .left
UIView.animate(withDuration: 0.3, animations: {
  self.view.layoutIfNeeded()
})

答案 1 :(得分:2)

此方法首先手动设置UIButton titleLabel帧的动画,然后设置内容对齐和内容边缘插入以保留UIButton默认行为。

CGRect frame = button.titleLabel.frame;
frame.origin.x = 10;
[UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
    button.titleLabel.frame = frame;
} completion:^(BOOL finished) {
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}];