在子视图中添加UIImage并添加约束-图像不会调整大小

时间:2018-10-02 02:09:27

标签: ios swift constraints swift4

我试图在子视图中添加图像,然后添加约束并调整其大小。

当我将translatesAutoresizingMaskIntoConstraints设置为true时,我的图像可以完美调整大小,但是约束不起作用。设置为false时,约束条件起作用,但是图像尺寸为常规尺寸,并且不会缩小。

这里是示例。 https://imgur.com/a/kgCQyUJ

let image = UIImage(named: "avatar")
        let imageView = UIImageView(image: image!)
        imageView.translatesAutoresizingMaskIntoConstraints = true

        imageView.frame = CGRect(x: 0,
                                 y: 0,
                                 width: 31,
                                 height: 29)

        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        imageView.clipsToBounds = true


        view.addSubview(imageView)
        view.addConstraints([


            // FIRST AVATAR

                    // leading
            NSLayoutConstraint(item: imageView,
                               attribute: .leading,
                               relatedBy: .equal,
                               toItem: view,
                               attribute: .leading,
                               multiplier: 1.0,
                               constant: 28),

                    // top
            NSLayoutConstraint(item: imageView,
                               attribute: .top,
                               relatedBy: .equal,
                               toItem: view,
                               attribute: .top,
                               multiplier: 1.0,
                               constant: 6),

                    // bottom
            NSLayoutConstraint(item: imageView,
                               attribute: .bottom,
                               relatedBy: .equal,
                               toItem: view,
                               attribute: .bottom,
                               multiplier: 1.0,
                               constant: 5)

            ])

我的错误:

    Probably at least one of the constraints in the following list is one you don't want. 
(
    "<NSAutoresizingMaskLayoutConstraint:0x2821c3700 h=--& v=--& UIImageView:0x12da069a0.midX == 15.5   (active)>",
    "<NSLayoutConstraint:0x2821d4410 H:|-(28)-[UIImageView:0x12da069a0]   (active, names: '|':UIView:0x12da067c0 )>"
)

1 个答案:

答案 0 :(得分:0)

似乎您缺少 trailing 约束。到目前为止,您只设置了领先顶部底部约束。

如果您要使用自动版式(使前,上,下,尾约束生效),请将translatesAutoresizingMaskIntoConstraints设置为false