Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 子视图(UILabel)不';t当放置在superview(UITextView)中时,不遵守约束_Ios_Uilabel_Uitextview - Fatal编程技术网

Ios 子视图(UILabel)不';t当放置在superview(UITextView)中时,不遵守约束

Ios 子视图(UILabel)不';t当放置在superview(UITextView)中时,不遵守约束,ios,uilabel,uitextview,Ios,Uilabel,Uitextview,我在UITextView实现中尝试了自己的“占位符” 我的做法是: 我在UITextView子类中创建一个UILabel,并设置UILabel的约束以匹配其超级视图的大小(UITextView) 这是我创建UILabel并将其分配给awakeFromNib()中名为placeholderLabel的类变量的代码: 下面的代码是我添加UILabel作为子视图的地方,我在awakeFromNib()中再次设置约束: 我还有一个属性,其中我设置了占位符的文本,其中我有一个didSet观察者,它设置了p

我在
UITextView
实现中尝试了自己的“占位符”

我的做法是:

我在
UITextView
子类中创建一个
UILabel
,并设置
UILabel
的约束以匹配其超级视图的大小(
UITextView

这是我创建
UILabel
并将其分配给
awakeFromNib()中名为
placeholderLabel
的类变量的代码:

下面的代码是我添加
UILabel
作为子视图的地方,我在
awakeFromNib()
中再次设置约束:

我还有一个属性,其中我设置了占位符的文本,其中我有一个
didSet
观察者,它设置了
placeholderLabel
的文本,然后调用
layoutifneed()
,以便在
UILabel
扩展到第二行(或第三行等)时重新计算约束:

问题是,我有以下结果:

UILabel
超出了它的SuperView边界(右侧),并且它似乎不遵守约束。我运行了可视化调试器,它确认了同样的事情:

似乎有一个宽度约束跟随
UILabel
的内容宽度,而不是跟随我设置的约束(在本例中,它创建的宽度为431,而superview的宽度为288)


有什么我错过的吗?

右边应该是负数

placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: - textContainerInset.right - 4).isActive = true

首先,必须为右约束的常量使用负值(或者-要使用正值-切换项目
placeholderLabel.rightAnchor
/
rightAnchor

然而真正的问题是,
UITextView
UIScrollView
的一个子类。在您的例子中,添加带有大文本的
UILabel
作为子视图,并将其边缘约束到textview的边缘,会导致textview的
contentSize
增长。文本视图可以水平滚动

在添加标签之前和之后打印文本视图的
contentSize
会导致宽度的不同值(之前:335.0,之后:505.0)

证明:

可以通过不创建右侧而是创建宽度约束来解决该问题:

// placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -(textContainerInset.right + 4)).isActive = true
placeholderLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -(textContainerInset.left + 4 + textContainerInset.right + 4)).isActive = true

我也试过了,这不是问题所在(如果你看到约束是如何解决的,额外的距离只有4个点,标签延伸到了这一点之外),常数显然不是问题所在。即使通过放置10,它仍然不能解决根本的问题。我认为当你编辑时,插入在运行时被更改,并且大于4,但是是的,这很奇怪。你能显示你的
UITextView
子类吗?看看发生了什么,我猜标签,就像在滚动视图中一样,正在设置文本视图的内容大小,这不是您想要的。您完全正确。经验教训:首先检查文档中的继承
var placeholder: String = "" {
    didSet {
        placeholderLabel.text = placeholder
        layoutIfNeeded()
    }
}
placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: - textContainerInset.right - 4).isActive = true
// placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -(textContainerInset.right + 4)).isActive = true
placeholderLabel.widthAnchor.constraint(equalTo: widthAnchor, constant: -(textContainerInset.left + 4 + textContainerInset.right + 4)).isActive = true