我在 Storyboard上设置了一些自定义按钮,我试图在代码中重新创建它们,但不知何故,尽管在 CGRectMake 函数中使用了相同的参数,但我没有获得正确的位置。另一个问题是,自动调整大小 mask 在代码中不起作用,因为我突出显示了左侧、底部和右侧支柱,因此按钮在 3.5 英寸和 4 英寸屏幕尺寸中保持位置,但是通过代码创建的按钮却不起作用做这个。我将发布 Storyboard中的 XML,然后发布我的代码来显示我的确切含义。在编写代码之前,先介绍一下我正在尝试做的事情。我在通过 Storyboard设置的项目中跨多个 Controller / View 有这些自定义按钮。我现在正在尝试以编程方式使用 Controller 中的按钮创建一个单独的 Controller ,然后让我的其他 Controller 继承此 Controller ,以便万一我需要进行修改,这些只需要做一次。
这是我的代码:
这是 Storyboard中的 XML:
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" id="iz0-cT-TPO">
<rect key="frame" x="0.0" y="357" width="106" height="60"/>
<autoresizingMask key="autoresizingMask" flexibleMinY="YES"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="15"/>
<state key="normal" image="Anotpressed.png">
<color key="titleColor" red="0.19607843459999999" green="0.30980393290000002" blue="0.52156865600000002" alpha="1" colorSpace="calibratedRGB"/>
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<state key="highlighted" image="Apressed.png">
<color key="titleColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</state>
</button>
我的 View Controller 中的等效代码是:
(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
UIButton *AButton=[UIButton buttonWithType:UIButtonTypeCustom];
[AButton setFrame:CGRectMake(0, 357, 106, 60)];
[AButton setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin];
[AButton setImage:[UIImage imageNamed:@"Anotpressed"] forState:UIControlStateNormal];
[AButton setImage:[UIImage imageNamed:@"Apressed"] forState:UIControlStateHighlighted];
[AButton setEnabled:YES];
[self.view addSubview:AButton];
}
目前我正在做的是将 Storyboard按钮保留在适当的位置,然后使用编程按钮从 View Controller 继承,以查看它们是否相同,并且我发现我的编程按钮比 Storyboard按钮,即使它们具有相同的坐标等。
对于这个问题的冗长,我深表歉意,但我想提供我想要实现的目标的完整图片。首先,如何以编程方式重新创建相同的按钮,其次,这是(继承/子类化)在我的项目中重新创建这些按钮的正确方法吗?
最佳答案
flexibleMinY
声明如果父 View 调整大小, Storyboard中的 View 可以重新定位。可能发生的情况是, View 以特定大小加载,但会调整大小以适应可用的屏幕空间。例如,如果 Storyboard是为 iPhone 4 屏幕尺寸设计的,但在新的 iPhone 5 屏幕分辨率上显示。
因为您在 viewDidAppear
中添加了按钮,所以大小调整已经发生。按钮已向下移动了一点,不再位于原来的位置。
您可以尝试在 viewDidLoad
中添加按钮,该按钮可能在显示原始 View 并调整其大小之前被调用。还要将相同的 autoresizingMask
添加到您的按钮。
或者确保原始按钮的 y 位置是固定的而不是灵活的。
关于ios - Storyboard UIButton 的等效代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507774/