我有一个用于从网络加载图像的视图控制器。图像通常会比视口大得多,因此我将其缩小并将其放置在 UIImageView 中。问题是它不想与视口的顶部对齐。我将如何解决这个问题。这是代码:
- (void)viewDidLoad
{
NSURL *imageURL = [NSURL URLWithString:[[self exhibit] image]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
UIImageView *iv = [[UIImageView alloc] initWithImage:image];
[iv setContentMode:UIViewContentModeScaleAspectFit];
[iv setTranslatesAutoresizingMaskIntoConstraints:NO];
[[self view] addSubview:iv];
[self setImageView:iv];
NSDictionary *nameMap = @{@"imageView" : [self imageView]};
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[imageView]-10-|"
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:nameMap];
[[self view] addConstraints:horizontalConstraints];
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[imageView]"
options:NSLayoutFormatAlignAllTop
metrics:nil
views:nameMap];
[[self view] addConstraints:verticalConstraints];
NSLog(@"%@", NSStringFromCGRect([[self imageView] frame]));
}
最后的日志显示 UIImageView 是原始图像大小的大小而不是缩小版本。我假设这是问题所在,但我不确定如何解决它。