【问题标题】:Adding UIImage in Subview and Adding Constraints - Image does not resize在子视图中添加 UIImage 并添加约束 - 图像不会调整大小
【发布时间】:2018-10-02 02:09:27
【问题描述】:

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

当我将 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 )>"
)

【问题讨论】:

    标签: ios swift constraints swift4


    【解决方案1】:

    您似乎缺少 trailing 约束。到目前为止,您只设置了 leading、top、bottom 约束。

    如果您想使用自动布局(让前导、顶部、底部、尾随约束起作用),请将 translatesAutoresizingMaskIntoConstraints 设置为 false。

    【讨论】:

    • 您是否尝试将图像设置在位置 {x: 28, y: 6} 且大小为 {width: 31, height: 29} 且具有自动布局约束?
    • 我设置了约束高度和宽度,现在它可以工作了!!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多