在另外两个视图之间插入视图



我已经为 IOS 目标 c 编程很长时间了,仍然在这样的情况下,每次执行简单的 UI 操作时开始计算距离对我来说感觉很疯狂:

假设我有一个带有几个标签的页面:

NAME : MATAN
MUSIC : TECHNO
AGE : 26

现在在某些特定情况下,我想在"MUSIC"和"AGE"之间再插入一个标签。

通常我会检查新标签的高度,并通过代码向下移动"AGE"标签。

太疯狂了,我还没有找到比这更好的方法,因为在处理更复杂的视图时,这变得很难!

有什么建议吗?

我建议你把它全部放在UITableView中,它正是为这类东西而设计的,并且具有插入/删除单元格的机制。

鉴于您必须添加的样板代码数量,用于此用途的 UITableView 有点矫枉过正。更好的解决方案是使用两个重叠的容器视图控制器,每个控制器都包含所需标签的正确固定布局。可以分别以编程方式启用和禁用这两个容器。有关一些示例,请参阅下面的 Apple 指南:

https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html

> Somone 提到使用约束。 这应该让你为这种事情指明正确的方向

self.automaticallyAdjustsScrollViewInsets = NO;
UILabel *label1 = [[UILabel alloc] init];
UILabel *label2 = [[UILabel alloc] init];
label1.text = @"NAME : MATAN";
label2.text = @"AGE : 26";
[self.view addSubview:label1];
[self.view addSubview:label2];
[label1 setTranslatesAutoresizingMaskIntoConstraints: NO];
[label2 setTranslatesAutoresizingMaskIntoConstraints: NO];
NSDictionary * viewsDictionary = NSDictionaryOfVariableBindings(label1, label2);
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[label1]-20-|" options:0 metrics: 0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[label2]-20-|" options:0 metrics: 0 views:viewsDictionary]];
NSArray * vertConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[label1]-10-[label2]" options:0 metrics: 0 views:viewsDictionary];
[self.view addConstraints:vertConstraint];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    UILabel *label3 = [[UILabel alloc] init];
    label3.text = @"MUSIC : TECHNO";
    [label3 setTranslatesAutoresizingMaskIntoConstraints: NO];
    [self.view addSubview:label3];
    NSDictionary * viewsDictionary = NSDictionaryOfVariableBindings(label1, label2, label3);
   [self.view removeConstraints:vertConstraint];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[label3]|" options:0 metrics: 0 views:viewsDictionary]];
    NSArray * newVertConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[label1]-10-[label3]-10-[label2]" options:0 metrics: 0 views:viewsDictionary];
    [self.view addConstraints:newVertConstraint];
});

您始终可以使用 tableViews 来简化它。

如果没有,请阅读有关约束的内容。也许你已经知道了。但是,如果您可以正确地做到这一点,它们将是一个很大的帮助。

在此处阅读有关约束的更多信息

最新更新