如何在应用自动布局的情况下动态移动 UIView?

How to move a UIView dynamically with auto layout applied?

我有一个 UISegmentedcontrol(有 2 个片段)和一个 UIView。由于最小段数为2,我不想隐藏segmentedcontrol并添加UILabel

这是它在模拟器中的样子:

(红色的是UIView。)

这是我的代码:

[self.segment setHidden:YES];

CGRect segmentFrame = self.segment.frame;
segmentFrame.size.width /= 2;

UILabel *myLabel= [[UILabel alloc] initWithFrame:segmentFrame];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell.contentView addSubview:myLabel];

如上图所示,我应用了自动布局。当隐藏 view 并添加 label 时,view 不会移到左侧。所以我尝试以编程方式移动它(应用自动布局时可能不应该这样做):

CGRect myViewFrame = self.myView.frame;
myViewFrame.origin.x -= segmentFrame.size.width;
self.myView.frame = myViewFrame;

还是不行。我的问题是:当 segmentedcontrol 隐藏时,如何让 view 向左移动?

为前导 space 添加约束到超级视图。在你的 .h:

IBOutlet NSLayoutConstraint *leftSpace;

将其从 Interface Builder 中的连接选项卡拖到您为前导 space 设置的约束到超级视图。无论您尝试在 .m 文件中以编程方式将其移动到何处,请将 leftSpace 属性 设置为您想要的宽度,如下所示:

leftSpace.constant = *the width you would like*;

希望对您有所帮助!

如果您使用 autolayout,更好的方法是以编程方式修改 autolayout constraints

按照以下步骤操作:

在您的 viewController.h 文件中创建一个 IBOutlet :

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameButtonVerticalConstraint;

现在将它与相关的自动布局约束连接起来:

现在您可以像这样简单地更改约束:

self.nameButtonVerticalConstraint.constant=25;

如果你想要更平滑的过渡,你可以把它放在动画块中:

[UIView animateWithDuration:1.2 delay:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
    self.nameButtonVerticalConstraint.constant=50;
    [self.view layoutIfNeeded];
} completion:nil];

编辑:这里是 this 文章的摘录

If other constraints will be affected because of the update to the constraint above, the following must also be called:

 [viewForUpdate setNeedsUpdateConstraints];

Now, animate your view by calling layoutIfNeeded inside your animation block.

将分段控件的宽度约束连接到 属性 并以编程方式将其值更改为 0,然后重新布局视图(您可能还希望将分段控件和视图之间的间隙归零 - 使用那里的方法相同)。