如何为动态创建的控件实现自动布局?

时间:2014-10-30 11:39:42

标签: objective-c iphone autolayout

我动态创建了一些控件显示在设备的底部,因为我需要根据设备高度为所有控件提供框架。但是当设备高度发生变化时,这很复杂,我的代码是

-(void)viewWillAppear:(BOOL)animated
{

    if([[UIScreen mainScreen]bounds].size.height==568)
    {
        xaxis=25;
        yaxis=350;
    }
    else
    {
        xaxis=25;
        yaxis=260;
    }

    UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(xaxis+35, yaxis+35, 250, 50)];

    label1 =@“This is first Label;

    UILabel *label2=[[UILabel alloc]initWithFrame:CGRectMake(xaxis+100, yaxis+50, 120,50)];

    label2.text=@"This is second Label";


    [self.view addSubview: label1];
    [self.view addSubview: label2];

}

任何人都可以建议如何为这些控件实现自动布局,并且在启用个人热点时应该进行调整。

1 个答案:

答案 0 :(得分:0)

您需要以编程方式创建所有自动布局约束。 只需使用addConstraint方法,如下所示

CGFloat bottom = 10;
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label1 attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:bottom]];

您还需要创建添加其他约束。