ios - 使用视觉格式化语言在代码中自动布局 UIViewController

标签 ios objective-c uiview uiviewcontroller autolayout

我想在代码中使用视觉格式化语言使用自动布局将 View emptyAddButton 放置在左下角。这是我目前的方法。

初始化按钮 emptyAddButton,一个自定义的 UIViewController:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
...
        emptyAddButton = [[AddCardViewController alloc] init];
        [emptyAddButton.view setFrame:CGRectMake(50, 300, 190, 65)]; //to define width + height. x, y is random and should be overwritten by auto auto layout
        [self addChildViewController:emptyAddButton];
        [emptyAddButton.view setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.view addSubview:emptyAddButton.view];
...
}

为左下角位置 + 填充分配自动布局 (10)

-(void)viewWillAppear:(BOOL)animated{
...
    NSDictionary *viewToLayout = [NSDictionary dictionaryWithObject:emptyAddButton.view forKey:@"emptyAddButton"];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(10)-[emptyAddButton]"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:viewToLayout]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat: @"V:[emptyAddButton]-(10)-|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:viewToLayout]];
...
}

目前 emptyAddButton 根本不显示。

知道如何正确定位 View 吗?

最佳答案

您不能设置框架、关闭自动调整大小蒙版并添加约束 - 它会丢弃您的框架并重新计算为零宽度和高度。您可以通过注销 View Controller 的 subview 来确认这一点。

也将大小添加到 VFL 字符串:

"H:|-(10)-[emptyAddButton(==190)]"

垂直约束也一样。

顺便说一句,将 View 的创建和约束的设置分开没有任何好处。一次完成所有操作(我会在 viewDidLoad 中完成)。目前,每次出现 View 时您都在重新创建约束。

关于ios - 使用视觉格式化语言在代码中自动布局 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191077/

相关文章:

objective-c - 沿二次曲线对 View 的中心点进行动画处理

ios - 添加CocoonJS iOS WebView +插件后,iOS PhoneGap插件停止工作

ios - 如何在表格 View 单元格中添加复选框?

ios - 为什么 dequeueReusableCellWithIdentifier 会导致我的整个应用程序崩溃/挂起?

iphone - 使用 timeIntervalSince 1970 的数学题

ios - 是否使用 Core Data?

iOS9:在另一个以编程方式添加的 View 中居中以编程方式添加的 View

ios - Swift-tvOS 解雇 UIAlertController

ios - 在 Swift 中使用 PageViewController 设置 NSTimer

ios - 在可移动的 UIView 中移动 UILabel