简体   繁体   中英

Resize UIImageView by changing frame

I have added a UIImageView in storyboard with a default image. In the code, I am updating the image at runtime and also adjusting the frame.

mainImageView.sd_setImage(with: NSURL(string: urlString) as URL?, completed: {
        (image, error, cacheType, url) in
        self.setPoints()
    })

public func setPoints() {
    mainImageView.frame = CGRect(x:x, y:0, width:(mainImageView.image?.size.width)!/1.7, height:(mainImageView.image?.size.height)!/1.7)
    mainImageView.contentMode = .scaleAspectFill
    mainImageView.setNeedsDisplay()
    mainImageView.reloadInputViews()
    mainImageView.updateConstraintsIfNeeded()
}

I read various posts on stack overflow and tried resizing the imageivew using above methods but no luck. Is there any other way for resizing the imageview?

You should disable pregenerated constraints. The most simple way is to use autoresizing masks instead of constraints for animating view.

mainImageView.translatesAutoresizingMaskIntoConstraints = true

You can put this code to your -viewDidLoad method or just above mainImageView.sd_setImage(with:...

And last but not least you need to call layoutIfNeeded within the block.

self.view.layoutIfNeeded()

It looks like you are using autolayout to size your image view, which would explain why manually setting the frame isn't doing anything. You need to modify the constraints that are determining the size of the image view, and then call mainImageView.layoutIfNeeded() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM