当标签更改文本时,为什么会导致图像超出图像视图的边界?

时间:2017-04-06 20:37:50

标签: ios objective-c iphone xcode

不确定如何简明扼要地提出这个问题。我有一个动画的图像。图像从200x200开始,缩小到0x0,然后再放大到200x200。我正在使用滑块来设置图像的animationDuration。我使用相同的滑块来设置标签的文本,其中包含滑块选择的值,例如如果滑块设置为3,则标签显示3.00。

问题在于,在移动滑块后设置标签的文本时,图像将以大于200x200的某个值启动动画序列。如果我注释掉设置标签文本的代码,我仍然可以改变图像的动画速度,它仍然保持在我设置的范围内。

这是ViewController.m文件:

import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *image;

- (IBAction)animate:(id)sender;

- (IBAction)stopAnimate:(id)sender;

@end

@implementation ViewController
//global variables:
//height and width
float h, w;

//boolean to set default animation status
bool isAnimated = YES;

- (void)viewDidLoad {
    [super viewDidLoad];

//set w and h to the width and height of the image, respectively
w = _image.bounds.size.width;
h = _image.bounds.size.height;


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)numSliderValueChange:(id)sender {
    //when the user moves the slider, show the new value in the lable
    [_lblAnimationDuration setText:[NSString stringWithFormat:@"%.2f", [_numSlider value]]];
}

- (IBAction)animate:(id)sender {
    //keeps the image animated until stop is clicked
    isAnimated = YES;

    [UIView animateWithDuration:[_numSlider value] delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        CGRect rect = _image.bounds;

        //set w (h) to the difference of the bounds of the rect and the image w (h)
        rect.size.width = w - rect.size.width;
        rect.size.height = h - rect.size.height;

        //assign rect to the image bounds
        _image.bounds = rect;

    } completion:^(BOOL finished) {
        if (finished) {
            if (isAnimated) {
                [self animate:sender];
            }
        }
    }];
}

- (IBAction)stopAnimate:(id)sender {
    //changes isAnimated to NO when "Stop" is clicked, stopping the image's animation
    isAnimated = NO;
}

@end

当更改标签文本时,图像将扩展到应用程序的大约一半,持续一个动画周期。否则,图像的大小永远不会超过您在图片中看到的大小。

Image should never be larger than this

1 个答案:

答案 0 :(得分:0)

如果您使用的是AutoLayout,我建议您通过为image的宽度和高度设置NSLayoutConstraint来修改image使用布局属性的大小

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *width;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *height;

要使用上面的属性,您必须在xib中为image添加高度和宽度约束,然后连接这两个属性。

然后,您可以使用这些约束来更改图像大小:

self.width.constant = yourNewValue