ios 以编程方式修改约束 Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35984877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:40:33  来源:igfitidea点击:

Modify constraint programmatically Swift

iosswiftnslayoutconstraint

提问by H4Hugo

I have the following view controller in my storyboard :

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

storyboard_mainVC

storyboard_mainVC

It will always have 6 image views that are, by default, equal in widths and heights. Each image view is constrained to the superview with : "equal heights" and a multiplier of 1/2.

它总是有 6 个图像视图,默认情况下,宽度和高度相等。每个图像视图都被限制在父视图中:“等高”和 1/2 的乘数。

However, before I load images inside, I read a property that gives me the desired height for an image (width will never be modified).

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

So my interface (at runtime) can look like this :

所以我的界面(在运行时)可以是这样的:

second_interface

第二个接口

I think I need to modify the multiplier constant but it's read-only.

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

I saw posts saying that we can update the constantproperty of the constraint but it's in points, I need it to work on every device.

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

Now what would you recommend ? Should I remove the constraint and add a new one ? If I don't remove it and try to apply a new height constraint, will it be removed automatically for me ?

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

Do I have to use pods like snapkit to do the job ?

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

Thanks for your help.

谢谢你的帮助。

EDIT

编辑

Here is the code I tried, but did not succeeded :

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

        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()
            }
        }

Am I doing it wrong ? I am unsure about the new height constraint though

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

采纳答案by H4Hugo

So this is the way I achieved this :

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

  • Create a constraint programmatically(height in my case) :

    // Drawing height property
    var drawingHeightConstraint: NSLayoutConstraint?
    
  • Deactivate old constraint and set the new one if needed

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

    // Drawing height property
    var drawingHeightConstraint: NSLayoutConstraint?
    
  • 停用旧约束并根据需要设置新约束

Note: heightContraints is an array of NSLayoutConstraint which contains my outlets

注意: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
        }

    }
  • Call layoutIfNeeded() right after (note: not sure when to call it)
  • 立即调用 layoutIfNeeded() (注意:不确定何时调用它)

回答by Karaban

The constraints constants are related to the content of the constrained element. That why you're getting such screen. The easiest way - create image with clear color and set it by default. After downloading completed just set new image for your imageView

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

Or you can set IBOutlet for your height constraint - and change it value for different situations i.e.

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

if(download.completed)
ibHeightOutlet.constant = imageView.frame.size.height;
else
ibHeightOutlet.constant = initialImageViewHeght.frame.size.height;

回答by FreeNickname

You can not change the multiplier for reasons unknown to me (some kind of Apple's implementation detail probably). You can remove a constraint and create a new one, however. You have to remove the old constraint, because it will not be removed automatically, and you'll get a conflict. Alternatively, you could create the first constraint (with the 0.5multiplier) with lower priority. This way you could keep it (autolayout would just ignore it), but I don't think it is a way to go, since why would you need that unnecessary constraint? Just delete it. As for third-party layout engines and libraries –?unfortunately, I can't give you any advice here.

由于我不知道的原因(可能是某种 Apple 的实现细节),您无法更改乘数。但是,您可以删除约束并创建新约束。您必须删除旧约束,因为它不会自动删除,并且会发生冲突。或者,您可以创建0.5优先级较低的第一个约束(使用乘数)。这样你就可以保留它(自动布局会忽略它),但我不认为这是一种方法,因为你为什么需要这种不必要的约束?删除它就行了。至于第三方布局引擎和库——不幸的是,我不能在这里给你任何建议。