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