UIView不根据子视图调整宽度?

时间:2017-10-01 09:30:56

标签: ios iphone swift uiview

我尝试创建可重复使用的UIView subclass,其中UILabelUIImageViewsubviews。我的视图子类应根据标签的宽度调整其宽度。

这是我的班级 -

class CustomView: UIView {
    private var infoLabel: UILabel!
    private var imageView: UIImageView!


    override init(frame: CGRect) {
        super.init(frame: frame)
        infoLabel = UILabel(frame: CGRect.zero)
        imageView = UIImageView(frame: CGRect.zero)
        addSubview(infoLabel)
        addSubview(imageView)

        infoLabel.backgroundColor = .white
        imageView.backgroundColor = .gray
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func updateConstraints() {
        super.updateConstraints()
        infoLabel.translatesAutoresizingMaskIntoConstraints = false
        imageView.translatesAutoresizingMaskIntoConstraints = false

        infoLabel.leadingAnchor.constraint(
            equalTo: self.leadingAnchor, constant: 5).isActive = true
        // infoLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        infoLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
        infoLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true

        imageView.leadingAnchor.constraint(
            equalTo: infoLabel.trailingAnchor, constant: 10).isActive = true
        //imageView.trailingAnchor.constraint(
            //equalTo: self.trailingAnchor, constant: 10).isActive = true
        //imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 25).isActive = true
        imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
        imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 5).isActive = true

    }
    internal func setText(_ text: String, andImage image: String){
        infoLabel.text = text
        imageView.image = UIImage(named: image)
    }
}

以下是我将其添加到视图中的方式 -

let aView: CustomView = CustomView(frame: CGRect(x: 20, y: 144, width: 120, height: 31))
view.addSubview(aView)
       aView.setText("my testing label", andImage: "distanceIcon")
        aView.backgroundColor = UIColor.red

我得到的结果就像添加了图片一样。(红色是我的自定义视图,白色是标签,灰色是图像) enter image description here

编辑:如果在Storyboard中添加视图,它正在工作,但是如果我通过上面提到的代码尝试它,它就无法正常工作。

1 个答案:

答案 0 :(得分:1)

您还必须在CustomView类实例上调用translatesAutoresizingMaskIntoConstraints = false:

  

self.translatesAutoresizingMaskIntoConstraints = false

还在自定义视图上添加前导和顶部约束以设置其位置:

customView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 200).isActive = true
customView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 200).isActive = true

不要忘记在imageView上添加尾随约束:

imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true