我制作了一个带有两个文字标签和两个按钮的自定义UIView
。它在创建时功能齐全,但现在我正在尝试在屏幕旋转时(即从纵向到横向)移动它。
即使UI元素似乎被正确移动,实际的UIView
框架最终会做出奇怪的事情,比如当它原来是正方形并且被设置为正方形时变成矩形但是不同的x,y位置。
我是如何看到这一点的,方法是将我的UIView
的背景颜色设置为黑色,然后观察我的背景图像是在绘制我想要绘制视图但是UIView
的背景的地方。变成一个不同的形状,被绘制在错误的地方。
这是我的代码:
- (void) moveControls
{
CGRect frame;
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
switch (orientation)
{
case UIDeviceOrientationPortrait:
case UIDeviceOrientationPortraitUpsideDown:
frame = CGRectMake(0, 120, 320, 320);
break;
case UIDeviceOrientationLandscapeLeft:
case UIDeviceOrientationLandscapeRight:
frame = CGRectMake(120, 0, 320, 320);
break;
case UIDeviceOrientationFaceDown:
case UIDeviceOrientationFaceUp:
case UIDeviceOrientationUnknown:
return;
}
[self setFrame:frame];
backgroundImage.frame = CGRectMake(0,0, frame.size.width, frame.size.height);
titleLabel.frame = CGRectMake(0,50,frame.size.width,frame.size.height/2);
titleLabel.numberOfLines = 0;
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.frame = CGRectMake(0,frame.size.height/3,frame.size.width,frame.size.height/3);
doneButton.frame = CGRectMake(frame.size.width - 154, frame.size.height - 90, 100, 34);
tellButton.frame =CGRectMake(54, frame.size.height - 90, 100, 34);
}
答案 0 :(得分:4)
没有真正回答所有问题,但解决了问题: ios: UIView's width and height after changing orientations is inaccurate?
view.center = view.superview.center;
view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
答案 1 :(得分:0)
使用:
- (void) moveControls
{
CGRect frame;
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
if (UIDeviceOrientationIsLandscape(orientation))
frame = CGRectMake(120, 0, 320, 320);
else
frame = CGRectMake(0, 120, 320, 320);
[self setFrame:frame];
backgroundImage.frame = CGRectMake(0,0, frame.size.width, frame.size.height);
titleLabel.frame = CGRectMake(0,50,frame.size.width,frame.size.height/2);
titleLabel.numberOfLines = 0;
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.frame = CGRectMake(0,frame.size.height/3,frame.size.width,frame.size.height/3);
doneButton.frame = CGRectMake(frame.size.width - 154, frame.size.height - 90, 100, 34);
tellButton.frame =CGRectMake(54, frame.size.height - 90, 100, 34);
}