代码之家  ›  专栏  ›  技术社区  ›  TheoK

子视图(UILabel)放置在superview(UITextView)中时不考虑约束

  •  0
  • TheoK  · 技术社区  · 7 年前

    我尝试了我自己的“占位符” UITextView “实施。

    我的做法是:

    我创建一个 UILabel 在a中 UITextView 子类,我设置 UILabel公司 以匹配其superview的大小( UITextView )。

    这是我创建 UILabel公司 并将其分配给名为 placeholderLabel 在里面 awakeFromNib() :

    placeholderLabel = UILabel()
    placeholderLabel.text = placeholder
    placeholderLabel.numberOfLines = 0
    placeholderLabel.lineBreakMode = .byWordWrapping
    placeholderLabel.textAlignment = .left
    

    下面的代码是我添加 UILabel公司 作为子视图,我在 awakeFromNib() :

    placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
    placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: textContainerInset.left + 4).isActive = true
    placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: textContainerInset.top).isActive = true
    placeholderLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: textContainerInset.right + 4).isActive = true
    placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: textContainerInset.bottom).isActive = true
    

    我还有一个属性,用于设置占位符的文本 didSet observer,设置 占位符标签 的文本,然后调用 layoutIfNeeded() 以便在以下情况下重新计算约束: UILabel公司 扩展到第二行(或第三行等):

    var placeholder: String = "" {
        didSet {
            placeholderLabel.text = placeholder
            layoutIfNeeded()
        }
    }
    

    问题是,我有以下结果:

    enter image description here

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

    enter image description here enter image description here

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

    有什么我错过的吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   André Slotta    7 年前

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

    但真正的问题是 UITextView 是的子类 UIScrollView 。在您的情况下,添加 UILabel 将大文本作为子视图并将其边约束到textview的边会导致textview的 contentSize 成长。文本视图可水平滚动。

    打印文本视图的 内容大小 添加标签前后的宽度值不同(之前:335.0,之后:505.0)。

    证明: https://www.dropbox.com/s/eogvl2c5r76c6cl/example.mov?dl=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
    
        2
  •  0
  •   Shehata Gamal    7 年前

    带右的应为负

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