简体   繁体   English

雨燕3 | 图像下的按钮标签并调整图像大小

[英]Swift 3 | Button Label under Image AND resize Image

I'm displaying an image on top of a button, everything is OK on iPhone 7 eg : 我在按钮上方显示图像,在iPhone 7上一切正常,例如:

在此处输入图片说明

I set button background color to blue to see the button frame. 我将按钮背景色设置为蓝色以查看按钮框架。

Since I set an aspect ratio on my button's parent view, the button size change on small device, and on iPhone 4S, I have : 由于我在按钮的父视图中设置了长宽比,因此在小型设备和iPhone 4S上,按钮的大小发生了变化,因此我有:

在此处输入图片说明

The button's images are not resized. 该按钮的图像未调整大小。 This is my code : 这是我的代码:

public extension UIButton {

    func setButtonWithTextBehindImage () {
        let spacing = CGFloat(0.0)

        let imageSize = self.imageView?.frame.size
        self.titleEdgeInsets = UIEdgeInsetsMake(0.0, -(imageSize?.width)!, -((imageSize?.height)! + spacing), 0.0)
        let titleSize = self.titleLabel?.frame.size
        self.imageEdgeInsets = UIEdgeInsetsMake(-((titleSize?.height)!), 0.0, 0.0, -(titleSize?.width)!)
    }
}

I tried to set contentMode .scaleAspectFit on button and on button imageView but everytime my imageSize is (30, 30) (the size of my @1x image) and it doesn't resize to button size. 我试图在按钮和按钮imageView上设置contentMode .scaleAspectFit,但是每次我的imageSize为(30,30)(@ 1x图像的大小)时,它不会调整为按钮大小。

How can I do ? 我能怎么做 ? TY TY

Could you provide a bit more context on how you're using the code snippet you provided (maybe some code that we could try running)? 您能否提供更多有关如何使用提供的代码片段的上下文(也许我们可以尝试运行一些代码)? Documentation from https://developer.apple.com/reference/uikit/uibutton/1624010-titleedgeinsets mention insets being applied after the rectangle has been sized to fit. 来自https://developer.apple.com/reference/uikit/uibutton/1624010-titleedgeinsets的文档提到了在调整矩形大小以使其适合之后应用的插图。 The time at which you're calling your function in the extension might have an effect on the expected resize not happening - as in, are you calling this when the view is loaded, after it appears, after subviews have been laid out. 在扩展中调用函数的时间可能会影响预期的未调整大小-例如,在加载视图,显示后,布置子视图之后,是否在调用此功能?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM