对象框架在运行时缩放,但保留恒定值,使得以编程方式放置项目 difficult/inaccurate

Object frames scale at runtime, but retain constant values, making placing items programmatically difficult/inaccurate

我正在为设备 运行ning iOS 8 及更高版本构建一个 iPhone 应用程序,因此该应用程序必须与所有 iPhone 兼容,因为4S.

首先,在故事板文件中,我创建了一个与4S屏幕大小相同的视图。在该视图中,我添加了一个 3 行网格,每行 4 个矩形。我添加了 Autolayout 约束,目前一切都运行良好。没有与错误放置的视图或冲突的约束等相关的错误或警告。矩形在所有 iPhone 模拟器上都能很好地缩放。

当我尝试以编程方式创建和放置按钮时出现问题。我的网格中的方块是需要放置这些按钮的占位符。因此,当我创建一个新按钮并设置它的框架时,我将它设置为等于网格上其中一个矩形的框架。当我 运行 应用程序在 4S 模拟器上运行时,它工作正常,但在所有其他模拟器(屏幕更大)上,按钮没有出现在正确的位置。

似乎正在发生的事情是,每个矩形在故事板编辑器中都有一个设置的 X 和 Y 值,并且当应用程序 运行s 在任何模拟器中时,X 和 Y 值都是保持不变,即使视图本身正在缩放。

更清楚地说,假设插槽 #2 的 x 值为 150,y 值为 200。每当我尝试通过将按钮的框架设置为插槽 #2 的框架来将按钮放置在插槽 #2 中时frame 然后 运行 应用程序,按钮的 X 和 Y 值始终分别设置为 150 和 200,而不是缩放以补偿设备屏幕尺寸的变化。插槽 #2 本身可以正确缩放,但设置为缩放 #2 的框架的按钮无论如何都被放置在 150/200。

有人遇到过这种情况吗?如果遇到过,您知道我如何让按钮的框架与屏幕上的其他元素一起缩放吗?

如果我没说清楚,请告诉我。也许我可以 post 一些图片来说明我的意思。

编辑:添加一些图像:

运行 在 4S 模拟器上。该卡出现在它应该在网格中的位置

这是在 6+ 模拟器上。如您所见,如果我 运行 在 4S 模拟器上使用它,该卡的显示位置基本上完全相同。不过,当我创建它时,我将它的框架设置为等于网格上第二个正方形的框架。

您需要使用自动布局来定位/调整大小,这样无论屏幕有多大,它们都会有相同的相对排列。 "Set the frame" 是自动布局的相反。不要设置任何框架;始终使用自动布局。

或者您可以使用帧,但时间就变得至关重要。您需要等到 viewDidLayoutSubviews 之后,因为只有到那时网格才具有它出现时的实际大小。如果您过早设置卡片的框架(例如在 viewDidLoad 中),您将使用笔尖网格大小,而不是运行时网格大小。

你不应该设置框架而不是使用 auto layout constraint。 在任何矩形 button/view 上创建位置卡按钮并 addsubview 它,然后以编程方式添加约束。试试 KVConstraintExtensionsMaster 库。

By Using KVConstraintExtensionsMaster library, put the below code from where you want to place new card upon Ractangle Buttons either 

   UIButton *placeCardButton = [UIButton prepareNewViewForAutoLayout];
   [placeCardButton setBackgroundColor:[UIColor redColor]];
   [self.secondRactangleButton prepareViewForAutoLayout];
   // here self.secondRactangleButton is IBOutlet reference.
   [self.secondRactangleButton addSubview:placeCardButton];

   // now adding all required constraints on the button
   [placeCardButton applyConstraintFitToSuperview];

Or Direct Without using library 

    UIButton * placeCardButton = [UIButton new];
    [placeCardButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [placeCardButton setBackgroundColor:[UIColor redColor]];
    [self.secondRactangleButton addSubview:placeCardButton];

    [self.secondRactangleButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[placeCardButton]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(placeCardButton)]];
    [self.secondRactangleButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[placeCardButton]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(placeCardButton)]];