AspectFit image inside an UIButton

て烟熏妆下的殇ゞ 提交于 2019-12-11 19:09:41

问题


I have an image looking like this

But it should look like this :

I added the line : cameraUIButton.imageView?.contentMode = .scaleAspectFit

It doesn't works BUT if i click on the button it fit !! What append in swift when you click on the button that recalculate the fit of the image ?

I already tried

        cameraUIButton.setNeedsDisplay()
        cameraUIButton.imageView?.setNeedsDisplay()
        cameraUIButton.imageView?.layoutIfNeeded()
        cameraUIButton.layoutIfNeeded()
        self.view.layoutIfNeeded()

and all in

viewDidLoad()
viewWillAppear()
viewDidAppear()

Nothing do what cliking on the button do, what else could i try ?


回答1:


When you do cameraUIButton.imageView?.contentMode = .scaleAspectFit it ensures that the image is scaled so as to fit the frame of the view, button in this case.

Try cameraUIButton.imageView?.contentMode = .aspectFit it will retain original image and not stretch it.




回答2:


I found the solution !!
You need to add

cameraUIButton.imageView?.adjustsImageSizeForAccessibilityContentSizeCategory = true

So the full code to aspectFit a vector image inside a button is :

cameraUIButton.imageView?.contentMode = .scaleAspectFit
cameraUIButton.imageView?.adjustsImageSizeForAccessibilityContentSizeCategory = true

I don't know why it's not trueby default as it's turned to it if you click on the button or if you animate it.




回答3:


Try this way

button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit



回答4:


  1. Go on storyboard give it a fixed width and height
  2. give is horizontal or vertical constraint according to your view.
  3. if you do these step you will get your image, also it will work fine in all device, don't forget to check clipOutOfBounds


来源:https://stackoverflow.com/questions/57904427/aspectfit-image-inside-an-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!