3

我遇到了这个非常特殊的问题,我无法修改 UIImageView 的框架。

我把它隔离到这个非常简单的例子中。从默认的单视图应用程序 xcode 模板开始,我在 Interface Builder 中添加了一个 UIImageView,将其链接到名为 testImage 的 ViewController 属性,然后在 ViewController.m 中添加:

-(void)viewDidAppear:(BOOL)animated{
    UIImageView* maskImage = [[UIImageView alloc] initWithFrame:self.testImage.frame];
    maskImage.image = self.testImage.image;
    maskImage.alpha = 0;
    [self.view addSubview:maskImage];
    self.testImage.frame = CGRectMake(10, 10, 10, 10);
}

它不起作用。测试图像坚定地保持在原来的位置。如果我不添加 maskImage 来查看,则该示例有效。而且,是的,我确定我没有用 maskImage 覆盖目的地。

如果我不使用 IB 来放置图像,而是使用:

self.testImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 300, 300)];
self.testImage.image = [UIImage imageNamed:@"jim-105.png"];
[self.view addSubview:self.testImage];

在 viewDidLoad 中,一切都按预期工作。

我也尝试将图像放在 IB 中,然后在 viewDidLoad 中设置其属性,但效果相同。我一直在 Xcode5 中尝试这个。我在这里无法访问以前的 Xcode,我不确定这是预期的行为(如果是,为什么)或者这是一个错误?

4

1 回答 1

8

I'd expect precisely the behavior you describe if you were using auto layout, in which attempts to adjust the frame can be thwarted when constraints are reapplied (which can happen with the most incidental of events, such as adding another view to the main view) and the frame will be recalculated. If you have an autolayout view with constraints, to change its size you change its constraints.

If you're wondering why the programmatically created testImage works as expected, it's because by default, the programmatically created view has translatesAutoresizingMaskIntoConstraints turned on. Thus, attempts to change the frame persist.

If you're using autolayout and want to change the frame, you can accomplish this by adding IBOutlet references for the constraints in Interface Builder. Let's say you had top, leading, width and height constraints for your view. You could then change it's frame (in this example, to CGRect(0, 100, 300, 200)) with:

self.imageViewLeadingConstraint.constant = 0;
self.imageViewTopConstraint.constant = 300.0;
self.imageViewWidthConstraint.constant = 300;
self.imageViewHeightConstraint.constant = 200;

Clearly, you need those four IBOutlet references, but once you do that, it's quite easy.

于 2013-09-28T12:42:59.010 回答