OGeek|极客世界-中国程序员成长平台

标题: ios - 如何灵活地在表格中定位 UIbuttons? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:16
标题: ios - 如何灵活地在表格中定位 UIbuttons?

我需要像这样在垂直列表中灵活地定位 UIButton:

A
B
C
D

问题是它需要灵活,就像缺少 B 时它应该看起来像:

A
C
D

所以应该没有空格,但 UIButton 应该向上移动

现在我像这样以编程方式定位 UIButton,但只有在我关闭 Autolayout 时这在 iOS7 中才有可能

但这反过来又需要以编程方式定位所有其他元素——尤其是在屏幕底部——我不想这样做。

我怎样才能以这种方式定位 UIButton,而不必以编程方式在屏幕上定位所有其他元素。

在 Android 中有 tablelayoutlinearLayout 可以自动处理!

编辑:

这一切都很痛苦,但这就是它的工作原理:

  1. position all your btns nicely left aligned, under each other so you can see them nicely in IB. at this stage the vertical spacing does not matter since we delete all these constranints created by IB anyway and programmatically add the vertical spacing we want later
  2. make sure now that there are only the constraints you want, and NO constraints created by IB that you do not want.
  3. In particular remove all vertical spacing constraints between the btns you want to programmatically reposition. Add the constraints you DO want one by one with IB by clicking on "Add constraint" in the grey popup. After that do not touch your layout anymore - you can easily mess it up!
  4. Use this code to reposition now A in relation to C for example. don't forget to set B invisible
UIView *superview = self.view;

NSMutableArray *mutableConstraintsArray =[[NSMutableArray alloc]init];
NSLayoutConstraint *constraint =       [NSLayoutConstraint constraintWithItem:A
                                                                    attribute:NSLayoutAttributeBottom

                                                                    relatedBy:NSLayoutRelationEqual toItem:C

                                                                    attribute:NSLayoutAttributeTop multiplier:1.0 constant:-20.0];//C is 20 points under A
[mutableConstraintsArray addObject:constraint];


for (int i = 0; i<mutableConstraintsArray.count; i++) {
    [superview addConstraint:mutableConstraintsArray[i]];
}

我在这里使用了 mutableConstraintsArray,所以我可以在这个时候添加多个约束!

很多努力恕我直言!

如果有更简单的方法,请更正/改进!

感谢 matt 为我指明了正确的方向。



Best Answer-推荐答案


Now I programmatically position the UIButtons programmatically like this, but this is only possible in iOS7 if I turn Autolayout off

那不是真的。您还可以以编程方式使用自动布局约束。假设已删除的按钮 B 对其上方的按钮 A 有一个约束,对其下方的按钮 C 有一个约束。当您删除 B 时,在 A 和 C 之间创建一个约束(以编程方式)并将该约束添加到它们的公共(public) super View 。完毕!现在 C 移动到位,D 移动到位,其余跟随。

关于ios - 如何灵活地在表格中定位 UIbuttons?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21354044/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4