避免视图约束干扰帧更改

时间:2019-01-21 17:08:17

标签: ios swift nslayoutconstraint

我正在使用一个滑块,该滑块随着移动会更新特定标签的值。滑块中的条具有垂直约束,以使其仅位于另一个元素的顶部,而另一个则使其水平居中。

如果我不更新标签,则用PanGestureRecognizer更改条形的位置非常有效:

@IBAction func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    if let meterView = recognizer.view {

        let minX = view.bounds.minX + meterView.bounds.width/2
        let maxX = view.bounds.maxX - meterView.bounds.width/2
        var resultingX = meterView.center.x + translation.x
        resultingX = resultingX < minX ? minX : resultingX
        resultingX = resultingX > maxX ? maxX : resultingX

        meterView.center = CGPoint(x: resultingX,
                              y: meterView.center.y)

        updateHeight(at: meterView.center.x/(maxX-minX))
    }
    recognizer.setTranslation(CGPoint.zero, in: self.view)
}

func updateHeight(at percentage: CGFloat) {
    let percentage = Float(percentage)
    heightLabel.text = String((maxHeight - minHeight)*percentage)
}

但是,由于约束,我想如果在平底锅的任何一点(在它的中间或在它的末端)更改标签,则条形图会跳回到水平中心。

如果在平移过程中消除了水平(或所有)约束,则当我进行轻微平移时,该条会完全跳出屏幕。

是否可以避免控制器将条形图更新回其约束定义的位置?

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:1)

删除使条形居中的约束,然后将其更改为与meterView(假设meterView是条形)与其超视角宽度有关的左约束:

meterView.left equal to Superview.left + constant

现在创建对名为meterViewLeftConstraint的约束的引用,并在handlePan中将约束的constant属性更新为resultingX

meterViewLeftConstraint.constant = resultingX

您现在无需设置center

我还建议您使用SnapKit进行约束,因为NSLayoutConstraint API非常混乱。

相关问题