With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?

后端 未结 8 479
花落未央
花落未央 2020-11-28 21:57

I want my UIImageView to grow or shrink depending on the size of what the actual image it\'s displaying is. But I want it to stay vertically centered and 10pts

8条回答
  •  隐瞒了意图╮
    2020-11-28 22:24

    For @algal case 3, all I had to do was

    class ScaledHeightImageView: UIImageView {
    
        override var intrinsicContentSize: CGSize {
    
            if let myImage = self.image {
                let myImageWidth = myImage.size.width
                let myImageHeight = myImage.size.height
                let myViewWidth = self.frame.size.width
    
                let ratio = myViewWidth/myImageWidth
                let scaledHeight = myImageHeight * ratio
    
                return CGSize(width: myViewWidth, height: scaledHeight)
            }
            return CGSize(width: -1.0, height: -1.0)
        }
    }
    

    This scales the height component of the intrinsicContentSize. (-1.0, -1.0) is returned when there is no image because this is the default behavior in the superclass.

    Also, I did not need to set UITableViewAutomaticDimension for the table with the cell containing the image view, and the cell still sizes automatically. The image view's content mode is Aspect Fit.

提交回复
热议问题