我在 UIViewController 中有一个 UIScrollView。它启用了滚动和缩放。它包含一个 UIImageView,当用户旋转设备时,图像保持居中。问题是,当设备旋转时,它实际上出现在左侧而不是中心,它应该停留在那里。这是我正在使用的代码。当 UIScrollView 旋转时调用设置框架:
-(void)setFrame:(CGRect)frame {
float previousWidth = self.frame.size.width;
float newWidth = frame.size.width;
[super setFrame:frame];
self.imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
[self setupScales];
self.zoomScale = self.zoomScale * (newWidth / previousWidth);
}
最佳答案
我在我的 uiscrollview 子类中使用以下 layoutsubviews 方法:
- (void)layoutSubviews {
[super layoutSubviews];
if ([[self subviews] count] == 0) {
return;
}
// center the image as it becomes smaller than the size of the screen
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = ((UIView*)[[self subviews] objectAtIndex:0]).frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = ((boundsSize.height - frameToCenter.size.height) / 2);
else
frameToCenter.origin.y = 0;
((UIView*)[[self subviews] objectAtIndex:0]).frame = frameToCenter;
}
关于iphone - UIImageView 旋转不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10504300/