Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...