如何防止 UIButton 的 imageView 占用整个 UIButton? [英] How to prevent imageView of UIButton from taking up entire UIButton?

查看:26
本文介绍了如何防止 UIButton 的 imageView 占用整个 UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以编程方式制作一个带有图标和标题的 UIButton(默认情况下,图标应位于标题旁边的左侧).但是,图标的尺寸非常大,因此当我使用 myButton.setImage() 时,图标会拉伸并占据整个按钮,标题也会消失.

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.

推荐答案

尝试将此扩展添加到 UIImage:

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!
    }
}

假设您有一个 1024x1024 的图标,希望将其调整为 40x40.只需这样做:

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)

这篇关于如何防止 UIButton 的 imageView 占用整个 UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆