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

界面生成器不会拉伸自定义视图的子视图

  •  2
  • Serega  · 技术社区  · 8 年前

    我已经创建了带有一个内部UILabel的自定义视图(FAQItemView),它被约束到superview的四个面。以下是此视图的源代码:

    import UIKit
    
    @IBDesignable class FAQItemView: UIView {
        var questionLabel: UILabel = UILabel()
    
       override init(frame: CGRect) {
            super.init(frame: frame)
            setup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setup()
        }
    
        func setup() {
            translatesAutoresizingMaskIntoConstraints = false
            addSubview(questionLabel)
            questionLabel.translatesAutoresizingMaskIntoConstraints = false
            questionLabel.textColor = UIColor.black
            questionLabel.textAlignment = .center
            questionLabel.numberOfLines = 0
            questionLabel.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            questionLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
            questionLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
            questionLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            questionLabel.text = "question"
            questionLabel.backgroundColor = UIColor.green
        }
    }
    

    我在Interface Builder中添加了FAQItemView,并将其宽度限制为200px。在这种情况下,FAQItemView的内部标签应延伸至FAQItemView的大小。运行应用程序时一切正常,但在Interface Builder中,标签以其默认(固有)大小定位在容器的左侧。

    示例项目位于 https://www.dropbox.com/s/u2923l8exqtg3ir/testapp1.zip?dl=0 . 此处FAQItemView具有红色背景,内部标签具有绿色背景。在运行时,红色不可见,因为标签具有绿色背景,但在Interface Builder中,红色也可见(在具有绿色背景的标签的右侧)

    有人能说出我做错了什么吗?

    提前谢谢。

    UPD: Screenshot of view in interface builder

    1 回复  |  直到 8 年前
        1
  •  2
  •   DonMag    8 年前

    哎哟。。。

    不设置 translatesAutoresizingMaskIntoConstraints = false 在自定义视图上 它本身 .

    所以,只需删除中的第一行 setup() :

    func setup() {
        //translatesAutoresizingMaskIntoConstraints = false
    

    这应该可以解决问题。