![](/img/trans.png)
[英]IBInspectable setTitle:forState on UIButton not working
[英]Why UIButton frame is reset by setTitle: forState: method
问题如下:
在某个时刻,按钮的位置会发生变化。 在此之后,还必须更改按钮的标题。
通过动画(UIView动画块)更改位置,并且当设置标题时,帧返回到原始值(在动画之前)。
那么......我该如何解决这个问题呢? 为什么会这样?
用代码更新
CGRect buttonFrame = self.button.frame;
buttonFrame.origin = CGPointMake(16, 80);
[UIView animateWithDuration:.4 animations:^{
[self.button setFrame:buttonFrame];
}completion:^(BOOL finished){
[self.button setTitle:@"Title" forState:UIControlStateNormal]; // can be here...
}];
无论我把setTitle放在哪里:ForState:方法,将帧恢复为原始值。
尝试在UIViewController上禁用Autolayout。 对我来说,有时Autolayout会导致一些讨厌的布局行为。 特别是当我使用动画时。
编辑
如果Autolayout开启,这对我有用:
[UIView animateWithDuration:.4 animations:^{
self.button.transform = CGAffineTransformMakeTranslation(-200,-200);
}completion:^(BOOL finished) {
[self.button setTitle:@"YourTitle" forState:UIControlStateNormal];
}];
使用自动布局时,不应设置任何帧。 相反,如果要更改按钮的位置,则应将IBOutlet设置为IB中的约束并修改其常量。 例如,如果你的按钮对屏幕的顶部和左侧有一个约束(我将它们称为leftCon和topCon),你可以这样做:
[UIView animateWithDuration:.4 animations:^{
self.leftCon.constant = 16;
self.topCon.constant = 80;
[self.view layoutIfNeeded];
}];
尝试使用transform
而不是更改框架:
button.transform = CGAffineTransformMakeTranslation(-100,-100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.