gpt4 book ai didi

ios - UIButton setAutoresizingMask 无法以编程方式工作

转载 作者:行者123 更新时间:2023-11-29 12:22:20 25 4
gpt4 key购买 nike

我在代码中添加了一个 UIButton,但是当我在不同的设备上测试它时,按钮不会正确调整大小和重新定位,但是当我在 Storyboard 上添加相同的按钮时,它的行为正常...... Storyboard 确实没有启用自动布局...

EDIT3:在下方添加了 UI 照片,较大的“Basics 2”按钮是 Storyboard定义的一个....其余的在代码中定义

Ui photo

EDIT2:当我查看行为正确的按钮的 Storyboard XML 时,它的定义如下,下面是完整的 Storyboard 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];

Storyboard 添加按钮,行为正确,设置如下,我哪里出错了?

enter image description here

最佳答案

设置UIViewAutoresizingFlexibleWidthUIViewAutoresizingFlexibleHeight

[button1 setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

当您使用 AutoresizingMask 在 IB 中添加按钮时,它会在午餐后自动调整大小。例如,屏幕宽度从 320(在 Storyboard中)增加到 540px(在设备上)并且按钮大小按比例增加。当您以编程方式添加按钮时,它只是添加,您应该根据屏幕大小手动计算按钮大小。自动调整按钮将在旋转时调用。所以你的宽度和高度应该这样计算:

CGFloat width  = k1 * [UIScreen mainScreen].bounds.size.width;
CGFloat height = k2 * width;

关于ios - UIButton setAutoresizingMask 无法以编程方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com