【问题标题】:Where to add topLayoutGuide constraint code在哪里添加 topLayoutGuide 约束代码
【发布时间】:2013-12-06 18:05:55
【问题描述】:

解决方案

想了个办法,把下面的代码放到我的子类导航控制器.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没有说清楚我应该把这段代码放在哪里(哪个类,哪个方法)(不知道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

【问题讨论】:

  • 我建议您将其作为方法添加到 UIButton 上的某个类别中。例如UIButton+CustomLayOut & 然后调用它。但是,您也可以在didFinishLaunchingWithOptions 中的appDelegate 类中实现

标签: ios autolayout


【解决方案1】:

在这种情况下,self 可以引用视图控制器。使用此代码,您正在为其视图添加约束,因此它可以在调用layoutSubviews 时设置子视图来布局子视图。如果您在 viewDidLoad 方法中添加此代码(并且我建议您在此处添加),您可以将出现的 myViewController 替换为 self

【讨论】:

  • 到@zbMax 那么代码中self和myViewController是什么关系呢?
  • 如果你把这段代码放在一个视图控制器中为它的视图和子视图设置约束,你应该用self替换myViewController
  • layoutSubviews 不应直接调用,它仅用于覆盖。如果需要布局子视图,请调用 setNeedsLayout 或 layoutIfNeeded
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
相关资源
最近更新 更多