Swift以编程方式添加的约束不起作用 [英] Swift programmatically-added constraints dont work

查看:253
本文介绍了Swift以编程方式添加的约束不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在滚动视图中有一个视图:

I have a view inside a scrollview:

现在,我想以编程方式将子视图添加到该视图。多数民众赞成在我的代码中做到这一点:

Now I want to add the child views to that view programmatically. Thats my code to do that:


  1. 子视图(有效)

  1. Child view (works)

//Adds header to the view again because it was removed in the clear() method
//Header is just a label
lv.addSubview(header)
header.leadingAnchor.constraint(equalTo: header.superview!.leadingAnchor).isActive = true
header.topAnchor.constraint(equalTo: header.superview!.topAnchor, constant: 2).isActive = true
header.widthAnchor.constraint(equalTo: header.superview!.widthAnchor).isActive = true
header.heightAnchor.constraint(equalToConstant: MainTabViewController.fontSize*3).isActive = true //Just a constant


现在我重复执行此代码:

Now I execute this code repeatedly:

private func makeTextLabel(text: NSAttributedString, bgColor: UIColor?, maxWidth: CGFloat?) -> UILabel {
    //Creates label
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    lv.addSubview(label)
    //Adjustments
    if(bgColor != nil) {
        label.backgroundColor = bgColor
    }
    label.textColor = UIColor.black
    label.attributedText = text
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    let width = maxWidth ?? lv.frame.size.width-8
    label.widthAnchor.constraint(equalToConstant: width).isActive = true
    label.heightAnchor.constraint(equalToConstant: heightForLabel(attributedText: label.attributedText, width: width)).isActive = true
    label.leadingAnchor.constraint(equalTo: lv.leadingAnchor, constant: 4).isActive = true
    let previousView = lv.subviews[lv.subviews.count-1]
    label.topAnchor.constraint(equalTo: previousView.bottomAnchor, constant:  10).isActive = true
    return label
}

所有标签都已添加,但约束根本不起作用。这是什么样子(当我执行两次以上方法时):

All the labels are added, but the constraints dont work at all. Here is what is looks like (when I execute the method above 2 times):

编辑:解决了主要问题。我现在正在使用StackView。( https://stackoverflow.com/a/59828434/6257435

The main problem is solved. I am using a StackView now.(https://stackoverflow.com/a/59828434/6257435)

我现在希望我的标签的边缘偏移,所以我使用这些线:

I now want my labels to have an offset to the edges, so I use those lines:

    label.leadingAnchor.constraint(equalTo: lessonStackView.leadingAnchor, constant: offset).isActive = true
    label.trailingAnchor.constraint(equalTo: lessonStackView.trailingAnchor, constant: -offset).isActive = true

但是当StackView似乎设置了x约束本身时,我得到了这个警告:

But as the StackView seems to set x-constraints itself, I get this warning:

无法同时满足约束条件。
以下列表中的约束中至少有一个是您不想要的约束。
尝试一下:
(1)查看每个约束,并尝试找出不期望的约束;
(2)查找添加了一个或多个不需要的约束的代码并进行修复。

UILabel:0x7f9c16c22c30'Falls dir die App gef\U00e4llt ...'(活动,名称:'|':JavaProf.MultipleContentsView:0x7f9c19024a60)>,


Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. ( "UILabel:0x7f9c16c22c30'Falls dir die App gef\U00e4llt...' (active, names: '|':JavaProf.MultipleContentsView:0x7f9c19024a60 )>", "", "" )

将尝试通过打破约束
来恢复

Will attempt to recover by breaking constraint

我该如何解决?

推荐答案

删除 width 锚点。您不必在意宽度(而且您也不是很清楚),而是使用 trailingAnchor 来代替:

Remove width anchor. You should not care about width (and you don't really know it), use trailingAnchor instead:

label.trailingAnchor.constraint(equalTo: lv.trailingAnchor, constant: -4).isActive = true

删除 heightAnchor ,而是让系统为您计算高度:

Remove heightAnchor, instead let system calculate the height for you:

label.setContentHuggingPriority(.required, for: .vertical)
label.setContentCompressionResistancePriority(.required, for: .vertical)

这应该是所有必需的。

但是,作为一个补充说明,而不是对前一个标签创建约束,您可以只使用 UIStackView

However, as a side note, instead of creating a constraint to previous label, you could just use a UIStackView.

这篇关于Swift以编程方式添加的约束不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆