ios - 保持 UIbuttons 背景图片的纵横比

标签 ios swift xcode uibutton

我一直在寻找几个小时,但我发现的只是旧答案,说它无法完成。

我有一个按钮,我希望背景图像尽可能大,同时保持其纵横比。无论我做什么,背景图像都会不断拉伸(stretch)。我试过了。

    var bluecircle = #imageLiteral(resourceName: "BLUE.png")

    monBreak.contentMode = UIViewContentMode.scaleAspectFit
    monBreak.setBackgroundImage(bluecircle, for: UIControlState.normal)

我真的需要制作一个 ImageView 并在其上放置一个不可见的按钮吗?这似乎欢迎许多可能出错的新事物。

我试过了

@IBOutlet weak var monBreak: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    var bluecircle = #imageLiteral(resourceName: "BLUE.png")

    let theimagebehindmonBreak = UIImageView(image: bluecircle)
    theimagebehindmonBreak.frame = CGRectFromString( "{{0,0},{40,40}}")
    monBreak.contentMode = UIViewContentMode.scaleAspectFit
    monBreak.addSubview(theimagebehindmonBreak)
    theimagebehindmonBreak.image=bluecircle
    theimagebehindmonBreak.contentMode = UIViewContentMode.scaleAspectFit

这使宽高比正确,但由于我希望布局是动态的,将其大小设置为固定值将不起作用,而且它没有居中。

起初我厌倦了像这样简单地应用按钮的约束

    var dacontraints = NSLayoutConstraint(monBreak.constraints)

但此时我收到错误消息“无法使用类型为‘{[NSLayoutconstraints]}”的参数列表调用类型为‘NSLayoutConstraint’的初始化程序

这让我很痛苦

最佳答案

听起来像是适合子类化的解决方案。

子类 UIButton,在 init 中添加一个 ImageView,将其调整到 frame,并正确设置 contentMode。

关于ios - 保持 UIbuttons 背景图片的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529717/

相关文章:

ios - 获取安全区域插入的顶部和底部高度

iphone - 新加载 View 中的导航 Controller

ios - 从中心点调整 UIImageView 的大小

iOS (Swift) 应用程序在 JSON 解析时崩溃

swift - 如何获得 iMovie 应用程序中看到的黑色标题栏?

ios - 为什么滑动手势识别器只能工作一次?

ios - 如何在 Swift4 中返回受线程影响的值

iPhone 到 iPhone 通信

ios - Xcode 11 向后兼容性 : "UIWindowScene is only available in iOS 13 or newer"

ios - 将图像加载到 UIScrollView 中