使用自动布局时在 Y 轴上移动 UIButton

Moving UIButton on Y axis while using Autolayout

我正在开发一个项目,在该项目中我为应用程序使用了自动布局/通用故事板。

我有一个 UIButton,我想在特定事件中移动到新位置。但是却不影响自动布局。所以它在每台设备上看起来都一样。

我已经通过这段代码成功地移动了按钮:

int deltaY = 100;

    [ans1 removeConstraints:ans1.constraints];
    ans1.frame = CGRectMake(ans1.frame.origin.x, ans1.frame.origin.y + deltaY, ans1.frame.size.width, ans1.frame.size.height);

但是按钮会在大约一秒内移回其原始位置。

为什么要删除 Button 中的约束?您可以创建按钮 Y 约束的 IBOutlet,然后更改该 Y 约束值,而不是删除约束

Select您要更改的 LayoutConstraint,然后控制将其拖到您的 .h 文件中

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

像这样更改您的约束值,

yAxisConstrain.constant = 0; //What ever the value you want.
[self.view layoutIfNeeded];