简体   繁体   English

通过更改框架来调整UIImageView的大小

[英]Resize UIImageView by changing frame

I have added a UIImageView in storyboard with a default image. 我在情节提要中添加了具有默认图像的UIImageView。 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. 我阅读了有关堆栈溢出的各种文章,并尝试使用上述方法调整imageivew的大小,但是没有运气。 Is there any other way for resizing the imageview? 还有其他方法可以调整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:... 您可以将此代码放到-viewDidLoad方法中或在mainImageView.sd_setImage(with:...

And last but not least you need to call layoutIfNeeded within the block. 最后但并非最不重要的一点是,您需要在块内调用layoutIfNeeded。

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() . 您需要修改确定图像视图大小的约束,然后调用mainImageView.layoutIfNeeded()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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