我在代码中添加了一个UIButton,但是当我在不同的设备上测试时,按钮不会调整大小并正确地重新定位,但是当我在Storyboard上添加相同的按钮时,它的行为正常...故事板的确如此没有启用Autolayout ......
EDIT3:在下面添加了UI的照片,较大的“Basics 2”按钮是故事板定义的一个....其余的在代码中定义
EDIT2:当我在Storyboard XML中查看行为正确的按钮时,它的定义如下,现在完整的故事板XML
<button hidden="YES" autoresizesSubviews="NO" opaque="NO" contentMode="center" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" id="ujO-uz-KyO">
<rect key="frame" x="30" y="100" width="116" height="70"/>
<autoresizingMask key="autoresizingMask" flexibleMinX="YES" widthSizable="YES" flexibleMaxX="YES" flexibleMinY="YES" heightSizable="YES" flexibleMaxY="YES"/>
<inset key="imageEdgeInsets" minX="0.0" minY="27" maxX="72" maxY="0.0"/>
<state key="normal" image="greenp.png" backgroundImage="basics2.png">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
</button>
我添加了这样的按钮(编辑使用下面建议的代码,仍然不起作用)
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.frame = [[butLocArr objectAtIndex:x] CGRectValue];
button1.autoresizesSubviews = YES;
[button1 setAutoresizingMask: UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight];
//The view is a UiScrollView
[scrollChallengeView addSubview:button1];
故事板添加按钮,行为正确,设置如下,我哪里错了?
答案 0 :(得分:1)
设置UIViewAutoresizingFlexibleWidth
和UIViewAutoresizingFlexibleHeight
[button1 setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
当您使用AutoresizingMask在IB中添加按钮时,它会在午餐后自动恢复。例如,屏幕宽度从320(在故事板中)增加到540px(在设备上),按钮大小按比例增加。当您以编程方式添加按钮时,它只是添加了,您应该根据屏幕大小手动计算按钮大小。自动调整按钮将调用旋转。所以你应该像这样计算宽度和高度:
CGFloat width = k1 * [UIScreen mainScreen].bounds.size.width;
CGFloat height = k2 * width;
答案 1 :(得分:0)
您需要使用UIViewAutoresizingFlexibleMargins
即
[button1 setAutoresizingMask:UIViewAutoresizingFlexibleMargins];
或
[button1 setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
而不是
[button1 setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
答案 2 :(得分:0)
在那个IB设置中你得到了:
因此自动调整遮罩应为
button1.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;