ios - 在哪里添加topLayoutGuide约束代码

标签 ios autolayout

解决方案

找到了一个解决方案,将以下代码放入我的子类导航 Controller .m 文件的 viewDidLoad 方法中:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
        [[self view] setTranslatesAutoresizingMaskIntoConstraints:NO];

        id topGuide = [self topLayoutGuide];
        UIView * selfView = [self view];
        NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (selfView, topGuide);
        [[[self view] window] addConstraints:
         [NSLayoutConstraint constraintsWithVisualFormat:@"V:[topGuide]-0-[selfView]"
                                             options:0
                                             metrics:nil
                                               views:viewsDictionary]
        ];
        [[[self view] window] layoutSubviews]; // You must call this method here or the system raises an exception
    }
}

原帖

苹果的doc没有说清楚我应该把这 block 代码放在哪里(哪个类,哪个方法)(不知道代码中 self 指的是什么):

[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);
[myViewController.view addConstraints:
    [NSLayoutConstraint constraintsWithVisualFormat: @"V: [topGuide]-20-[button]"
                                                 options: 0
                                                 metrics: nil
                                                   views: viewsDictionary]
self.view layoutSubviews; // You must call this method here or the system raises an exception
];

我觉得上面的代码块有一些拼写错误,所以我认为应该是这样的:

[button setTranslatesAutoresizingMaskIntoConstraints: NO];
id topGuide = myViewController.topLayoutGuide;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (button, topGuide);
[myViewController.view addConstraints:
    [NSLayoutConstraint constraintsWithVisualFormat: @"V: [topGuide]-20-[button]"
                                                 options: 0
                                                 metrics: nil
                                                   views: viewsDictionary]
];
self.view.layoutSubviews; // You must call this method here or the system raises an exception

最佳答案

在这种情况下,self 可以引用 View Controller 。使用此代码,您可以向其 View 添加约束,以便它可以按照您在调用 layoutSubviews 时设置的方式布局 subview 。如果您在 viewDidLoad 方法中添加此代码(我建议您在其中添加它),您可以将 myViewController 替换为 self

关于ios - 在哪里添加topLayoutGuide约束代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20418548/

相关文章:

ios - UIWebView网页缓存,供离线查看

ios - 如何使用 Core Graphics 在我的触摸位置画一个圆圈?

ios 从代码中将 uiview 的约束添加到 uiscrollview

ios - 动画 UIView 在 TextField 焦点更改后更改框架位置

ios - 自动布局中心 x 对齐导致 iPhone 6 Plus 上的无限布局循环

ios - 嵌入固有大小的 View 会破坏动画

ios - 错误的语言代码 swift

ios - NSOperationQueues 中的信号量

ios - 暂停/玩卡住游戏

ios - "Magic Move"效果自定义转场