以编程方式修改约束Swift

H4H*_*ugo 12 ios nslayoutconstraint swift

我的故事板中有以下视图控制器:

storyboard_mainVC

它总是有6个图像视图,默认情况下,宽度和高度相等.每个图像视图都被约束到超级视图:"相等高度"和1/2的乘数.

但是,在我将图像加载到内部之前,我读取了一个属性,该属性为图像提供了所需的高度(宽度永远不会被修改).

所以我的界面(在运行时)可能如下所示:

second_interface

我想我需要修改乘数常数,但它是只读的.

我看到帖子说我们可以更新约束的常量属性,但它是分数,我需要它在每个设备上工作.

现在你会推荐什么?我应该删除约束并添加一个新约束吗?如果我不删除它并尝试应用新的高度约束,它会自动删除吗?

我是否必须使用像snapkit这样的pod来完成这项工作?

谢谢你的帮助.

编辑

这是我试过的代码,但没有成功:

        for (index, (drawing, ratio)) in drawingElements.enumerate() {
            drawingViews[index].image = UIImage(named: drawing)
            // update height constraint if ratio is different than defaut ratio of 1/2
            if ratio != 0.5 {
                heightConstraints[index].active = false
                let newHeightConstraint = NSLayoutConstraint(item: drawingViews[index], attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: ratio, constant: 0)
                drawingViews[index].addConstraint(newHeightConstraint)
                self.view.layoutIfNeeded()
            }
        }
Run Code Online (Sandbox Code Playgroud)

我做错了吗?我不确定新的高度限制

H4H*_*ugo 8

所以这就是我实现这个目标的方式:

  • 以编程方式创建约束(在我的情况下为高度):

    // Drawing height property
    var drawingHeightConstraint: NSLayoutConstraint?
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果需要,停用旧约束并设置新约束

注意:heightContraints是一个包含我的出口的NSLayoutConstraint数组

        for (index, (drawing, ratio)) in drawingElements.enumerate() {
        drawingViews[index].image = UIImage(named: drawing)

        // update height constraint if ratio is different than defaut ratio of 1/2
        if ratio != 0.5 {
            heightConstraints[index].active = false
            drawingHeightConstraint = NSLayoutConstraint(item: drawingViews[index], attribute: .Height, relatedBy: .Equal, toItem: drawingView, attribute: .Height, multiplier: CGFloat(ratio), constant: 0)
            drawingHeightConstraint!.active = true
        }

    }
Run Code Online (Sandbox Code Playgroud)
  • 紧接着调用layoutIfNeeded()(注意:不确定何时调用它)


小智 5

约束常数与受约束元素的内容有关。那就是为什么你得到这样的屏幕。最简单的方法-创建颜色清晰的图像并默认设置。下载完成后,只需为您的imageView设置新图像

或者,您可以为您的高度限制设置IBOutlet-并针对不同情况更改其值,即

if(download.completed)
ibHeightOutlet.constant = imageView.frame.size.height;
else
ibHeightOutlet.constant = initialImageViewHeght.frame.size.height;
Run Code Online (Sandbox Code Playgroud)