ContentMode does not work for images set to UIButton

Asked 2 years ago, Updated 2 years ago, 34 views

I want to set the contentMode of the image I set to UIButton, but it doesn't take effect.
The size of the UIButton is 180/44 and the size of the image is 44/44, but it is full.
Is there a way to change the size of the button to 44 only for the display size of the image?

let btn:UIButton=UIButton()
btn.frame = CGRectMake(0,0,180,44)
btn.setBackgroundImage(UIImage(named: "image.png"), forState:UIControlState.Normal)
btn.contentMode=UIViewContentMode.ScaleAspectFit
btn.imageView?.contentMode=UIViewContentMode.ScaleAspectFit
self.view.addSubview(btn)

ios swift

2022-09-30 16:04

1 Answers

The imageView in UIButton refers to the image set in setImage() instead of setBackgroundImage(), so you must specify:

let btn=UIButton()
btn.frame = CGRectMake(0,0,180,44)
btn.setImage(UIImage(named: "image.png"), forState:.Normal)
btn.imageView?.contentMode=.ScaleAspectFit
self.view.addSubview(btn)


2022-09-30 16:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.