简体   繁体   中英

How to prevent imageView of UIButton from taking up entire UIButton?

I am trying to make an UIButton programmatically with an icon and a title (as default, icon should be on the left next to the title). However, the icon is quite big in size so when I use myButton.setImage() the icon stretches and takes up the entire button, the title also disappears.

I also tried to set imageEdgeInsets but it does not make the title appear.

So is there any way to make the icon smaller (maybe .scaleToFit ) and the title appear again?

If not, how small the icon (relatively to the button) should I export?

Try adding this extension to UIImage :

extension UIImage {
    func resizeToBoundingSquare(_ boundingSquareSideLength : CGFloat) -> UIImage {
        let imgScale = self.size.width > self.size.height ? boundingSquareSideLength / self.size.width : boundingSquareSideLength / self.size.height
        let newWidth = self.size.width * imgScale
        let newHeight = self.size.height * imgScale
        let newSize = CGSize(width: newWidth, height: newHeight)
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return resizedImage!
    }
}

Say you have a 1024x1024 icon that you wish to resize as 40x40. Just do this:

var myIcon = UIImage(named: image)
myIcon = myIcon.resizeToBoundingSquare(40)

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