我在调整按钮宽度的动画时遇到一些麻烦。这是我的代码:
- (IBAction)profileButtonPressed:(UIButton *)sender {
UIImage *buttonProfileDefault = [[UIImage imageNamed:@"Profile_Button_Default"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
[sender setBackgroundImage:buttonProfileDefault forState:UIControlStateNormal];
UIImage *buttonProfileDefaultDown = [[UIImage imageNamed:@"Profile_Button_Default_Down"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
[sender setBackgroundImage:buttonProfileDefaultDown forState:UIControlStateHighlighted];
[sender setTitle:@"LOG OUT" forState:UIControlStateNormal];
sender.titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
sender.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Animate
CGRect originalFrame = sender.frame;
originalFrame.size.width = sender.frame.size.width+60;
[UIView animateWithDuration:1.5 animations:^{
sender.frame = originalFrame;
}];
}
它改变了按钮的宽度(除非我去掉改变标题的那段代码),但它不是通过动画来实现的。
有什么建议可能是错误的吗?
更新
因此,我设法对宽度变化进行动画处理,但将 setTitle 放在动画部分中,但它没有获得文本本身的正确宽度(下图)。我怎样才能做到这一点?
解决方案
所以我最终以编程方式放置了 uibutton。似乎自动布局导致了问题。
只有我一个人觉得这样还是 Objective C 中的很多东西都有点笨拙?!
最佳答案
我怀疑您的问题与内在内容大小有关。如果设置了(我认为是默认情况下),那么当您更改标题时,按钮将更改大小,没有动画,而无需您在代码中执行任何操作。有几种方法可以解决这个问题。我认为最简单的方法是将 IB 中按钮的大小扩大一点,即使是一个像素也足以让 IB 设置显式宽度(或者您可以自己设置)。然后在代码中,您可以执行以下操作:
-(IBAction)buttonClick:(UIButton *)sender {
[sender setTitle:@"Log Out Immediately" forState:UIControlStateNormal];
[self.button removeConstraint:self.lengthConstraint];
[UIView animateWithDuration:.5 animations:^{
self.button.frame = CGRectMake(self.button.frame.origin.x, self.button.frame.origin.y, 250, 44);
}];
}
self.lengthConstraint 是 IBOutlet,用于在 IB 中设置长度约束。
另一种方法是使用 NSTimer 更改约束方法中的常量。这是 WWDC 2012 演讲“掌握自动布局的最佳实践”中提到的方法之一:
-(IBAction)buttonClick:(UIButton *)sender {
[sender setTitle:@"Log Out Immediately" forState:UIControlStateNormal];
[NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(expandButton:) userInfo:nil repeats:YES];
}
-(void)expandButton:(NSTimer *) timer {
self.lengthConstraint.constant += 2;
if (self.lengthConstraint.constant > 170) [timer invalidate];
}
关于iphone - 动画调整 UIButton 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13575522/