Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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? See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
127 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...