gpt4 book ai didi

iphone - 动画调整 UIButton 的宽度

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:17:44 26 4
gpt4 key购买 nike

我在调整按钮宽度的动画时遇到了一些麻烦。这是我的代码:

- (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 放在动画部分,但它没有为文本本身获得正确的宽度(下图)。我怎样才能做到这一点?

enter image description here

解决方案

所以我最终以编程方式放置了 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 是在 IB 中设置的那个长度约束的 IBOutlet。

另一种方法是使用 NSTimer 更改约束方法中的常量。这是 WWDC 2012 talk“Best Practices for Mastering Auto Layout”中提到的方法之一:

-(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com