ios – 以编程方式实现视图的自动布局

前端之家收集整理的这篇文章主要介绍了ios – 以编程方式实现视图的自动布局前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个应用程序,其视图是以编程方式生成的.例:
  1. -(void)loadView
  2. {
  3. [super loadView];
  4.  
  5. // SET TOP LEFT BTN FOR NEXT VIEW
  6. UIBarButtonItem *topLeftBtn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil];
  7. self.navigationItem.backBarButtonItem = topLeftBtn;
  8. [topLeftBtn release];
  9.  
  10. // programmatically set up the view for cart tableView
  11. CGRect IoUTableViewFrame = CGRectMake(0,320,348);
  12. IoUTableView = [[UITableView alloc]initWithFrame:IoUTableViewFrame style:UITableViewStylePlain];
  13. [[self IoUTableView] setDelegate:self];
  14. [[self IoUTableView] setDataSource:self];
  15. [[self view] addSubview:IoUTableView];
  16.  
  17. // set up the summary label
  18. CGRect summaryTableFrame = CGRectMake(0,348,18);
  19. UILabel *summaryTableLabel = [[UILabel alloc] initWithFrame:summaryTableFrame];
  20. [summaryTableLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
  21. [summaryTableLabel setText:@" Summary"];
  22. UIColor *labelColor = UIColorFromRGB(MiddleBlueColor);
  23. [summaryTableLabel setBackgroundColor:labelColor];
  24. [summaryTableLabel setTextColor:[UIColor whiteColor]];
  25. [[self view] addSubview:summaryTableLabel];
  26.  
  27. // set up the summary table
  28. CGRect summaryTableViewFrame = CGRectMake(0,366,44);
  29. summaryTableView = [[UITableView alloc]initWithFrame:summaryTableViewFrame style:UITableViewStylePlain];
  30. [summaryTableView setScrollEnabled:NO];
  31. [[self summaryTableView] setDelegate:self];
  32. [[self summaryTableView] setDataSource:self];
  33. [[self view] addSubview:summaryTableView];
  34. }

是.我将在未来更新NIB并使用界面构建器和故事板,但我一年没有完成ios编程.

随着新的iPhone 5具有不同的屏幕尺寸,应用程序看起来不太好,我需要实现某种类型的自动布局.有没有办法以编程方式现在而不是使用IB?

非常感谢!

解决方法

是的,在NSLayoutConstraint中使用两种方法
  1. -(NSArray*)constraintsWithVisualFormat:options:metrics:views:
  2. -(NSLayoutConstraint*)constraintWithItem:attribute:relatedBy:toItem:attribute:
  3. multiplier:constant:

视觉格式语言全部打包成NSString
所以我以你的IoUTableView为例.

  1. [self.view addConstraints:[NSLayoutConstraint
  2. constraintsWithVisualFormat:@"|[IoUTableView]|"
  3. options:0
  4. metrics:nil
  5. views:NSDictionaryOfVariableBindings(IoUTableView)]];

管道符号“|”代表着超级视野的优势.
[]代表一个视图.
那么我们在那里做了什么,我们将IoUTableView的左右边缘挂接到其超级视图的左右边缘.

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

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

现在,这三个视图在每个边缘垂直连接,NSLayoutFormatAlignAllLeft将所有视图对齐左侧,他们将基于其他约束,在这种情况下,先前的约束.
()用于指定视图的大小.

有更多的不平等和优先级以及“ – ”间隔符号,而是check out the apple docs for that

编辑:更正了使用constraintsWithVisualFormat的示例,如方法签名所示.

猜你在找的iOS相关文章