自动布局阻止我更改视图的中心

Dan*_*row 4 ios autolayout nslayoutconstraint

我的应用程序的一个功能是自动裁剪图像.

基本的想法是有人会拍一张纸的照片(想想:收据),然后在确定纸张边框后自动裁剪图像.

我可以通过使用OpenCV来确定纸张的边框.所以,我接下来要做的就是更改每个指南的"中心"属性(只需2个水平线和2个垂直"线",可以手动拖动).

然后,在我拨打所有电话以改变4个指南中的每一个之后不久,有其他东西出现并再次设置"中心".(我已经覆盖了"setCenter"来证明这一点).该中心似乎被重置:[UIView(Geometry)_applyISEngineLayoutValues].

我无法弄清楚为什么会发生这种情况,或者如何阻止它,但它可能与约束有关.我的观点是一个简单的UIButton.当用户用手指敲击并拖动它时,会调用一个仅改变中心的动作例程.这有效.

但在另一个案例中,我提出了一个UIImagePickerController.选择图片后,我确定纸张边界,更改"指南"中心,然后在"_applyISEngineLayoutValues"中将它们全部设置回来.

知道这种情况下发生了什么吗?或者我如何设置视图的中心,并让它实际停留?

Fog*_*ter 12

自动版式的第一条规则是,你不能更新frame,boundscenter直接在视图中.

您必须更新与视图相关的约束,以便约束更新视图.

例如,你的第一条垂直线会有水平约束......

1. Leading edge to superview = some value.
2. Width = some value.
Run Code Online (Sandbox Code Playgroud)

这足以(水平地)将此线放在屏幕上.

现在,如果你想将这条线移到右边,你不能只改变center你必须这样做...

1. Create a property in you view controller like this...

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *verticalLine1LeadingConstraint;
// or if you're coding the constraint...
@property (nonatomic, strong) NSLayoutConstraint *verticalLine1LeadingConstraint;

2. Save the constraint in to that property...

// either use IB to CTRL drag the constraint to the property like any other outlet.
// or something like...

self.verticalLine1LeadingConstraint = [NSLayotuConstraint ... // this is the code adding the constraint...

[self.view addConstraint:self.verticalLine1LeadingConstraint];
Run Code Online (Sandbox Code Playgroud)

现在您有一个指向此约束的属性.

现在,当你需要"更新垂直线1的中心"时......

// Calculate the distance you want the line to be from the edge of the superview and set it on to the constraint...

float distanceFromEdgeOfSuperview = // some calculated value...

self.verticalLine1LeadingConstraint.constant = distanceFromEdgeOfSuperview;

[self.view layoutIfNeeded];
Run Code Online (Sandbox Code Playgroud)

这将更新视图的位置,您不会收到任何错误.