【问题标题】:How to implement auto layout for dynamically created controls?如何为动态创建的控件实现自动布局?
【发布时间】:2014-10-30 11:39:42
【问题描述】:

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

-(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];

}

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

【问题讨论】:

  • 使用约束来管理控件 3.5" 和 4"
  • 使用[parentView addConstraint:[NSLayoutConstraint constraintWithItem:...
  • 你能简单解释一下吗?

标签: objective-c iphone autolayout


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回复!我添加了底部值为 0 的约束,我的标签出现在底部和左侧,只出现了一些文字。为什么会这样?我需要给控件提供 NSLayoutAttributeLeft,NSLayoutAttributeWidth,NSLayoutAttributeHeight 约束?
  • @StackUser 添加子视图后尝试使用 [self layoutSubtreeIfNeeded] 方法。
  • 你可以编辑我的代码,让标签出现在屏幕底部吗?(即 label1 在 label2 上方)
  • @StackUser 只是根据需要在一些测试 nib 文件中创建约束,然后在您的类中以编程方式创建所有约束。密切关注您添加约束的对象。
猜你喜欢
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 2017-07-22
  • 2021-03-24
  • 1970-01-01
  • 2014-10-31
相关资源
最近更新 更多