实现以编程方式生成的视图的自动布局

我有一个应用程序的视图是以编程方式生成的。 例:

-(void)loadView { [super loadView]; // SET TOP LEFT BTN FOR NEXT VIEW UIBarButtonItem *topLeftBtn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationItem.backBarButtonItem = topLeftBtn; [topLeftBtn release]; // programmatically set up the view for cart tableView CGRect iouTableViewFrame = CGRectMake(0, 0, 320, 348); iouTableView = [[UITableView alloc]initWithFrame:iouTableViewFrame style:UITableViewStylePlain]; [[self iouTableView] setDelegate:self]; [[self iouTableView] setDataSource:self]; [[self view] addSubview:iouTableView]; // set up the summary label CGRect summaryTableFrame = CGRectMake(0, 348, 320, 18); UILabel *summaryTableLabel = [[UILabel alloc] initWithFrame:summaryTableFrame]; [summaryTableLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]]; [summaryTableLabel setText:@" Summary"]; UIColor *labelColor = UIColorFromRGB(MiddleBlueColor); [summaryTableLabel setBackgroundColor:labelColor]; [summaryTableLabel setTextColor:[UIColor whiteColor]]; [[self view] addSubview:summaryTableLabel]; // set up the summary table CGRect summaryTableViewFrame = CGRectMake(0, 366, 320, 44); summaryTableView = [[UITableView alloc]initWithFrame:summaryTableViewFrame style:UITableViewStylePlain]; [summaryTableView setScrollEnabled:NO]; [[self summaryTableView] setDelegate:self]; [[self summaryTableView] setDataSource:self]; [[self view] addSubview:summaryTableView]; } 

是。 我将会更新到NIB,将来会使用接口生成器和故事板,但是我一年没有做过ios编程。

随着新的iPhone 5有不同的屏幕尺寸,应用程序只是不好看,我需要实现某种自动布局。 有没有办法做到现在编程而不是使用IB?

非常感谢!

是的,通过在NSLayoutConstraint中使用两种方法

 -(NSArray*)constraintsWithVisualFormat:options:metrics:views: -(NSLayoutConstraint*)constraintWithItem:attribute:relatedBy:toItem:attribute: multiplier:constant: 

可视化格式语言全部打包成一个NSString所以我会拿你的iouTableView为例。

 [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[iouTableView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(iouTableView)]]; 

pipe道符号“|” 代表超级观点的优势。 []代表一个视图。 所以我们在那里做了我们把iouTableView的左右边缘连接到它的超视图的左边和右边。

视觉格式的另一个例子:让我们垂直钩住你的表格视图,摘要标签和汇总表。

 [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat: @"V:|[iouTableView(348)][summaryTableLabel(18)][summaryTableView(44)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:NSDictionaryOfVariableBindings(iouTableView, summaryTableLabel, summaryTableView)]]; 

现在,在每个边上垂直链接所有三个视图,NSLayoutFormatAlignAllLeft告诉所有的视图左alignment,他们将基于其他约束,在这种情况下,先前的约束。 ()用于指定视图的大小。

有一点更像不平等和优先事项,以及“ – ”间隔符号,但检查了苹果文档

编辑:更正了示例以使用方法签名中显示的constraintsWithVisualFormat。

除了Aplle提供的方法之外,您还可以使用Parus lib从代码中使用AutoLayout。

例如,您将能够指定:

 PVVFL(@"[view1]-20-[view2]").fromRightToLeft.withViews(views).asArray 

代替

 [NSLayoutConstraint constraintsWithVisualFormat:@"[view1]-20-[view2]" options:NSLayoutFormatDirectionRightToLeft metrics:nil views:views] 

您也可以将布局设置分组,混合VFL而不是VFL约束。 帕鲁斯能够防止常见的错误,区分位置参数 constriaints,并提供很好的自动完成支持。