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 - (Swift) 在 for 循环中使用带有 NSURLSession 的信号量

ios - Swift - UIAlertController 后操作

ios - 从数组中检索 TableView 单元格标签的值

iphone - UISearchbar 和 SearchDisplay Controller 未在 iOS7 中的状态栏下方延伸

objective-c - 有人能让我了解sortedArrayUsingFunction 的工作原理吗?

ios - iOS 上的 Facebook Deferred Deep Linking 是否有效,如何在商店发布应用程序之前对其进行测试?

ios - 导航栏按钮图片

ios - 将按钮绑定(bind)到 View iOS swift 的右上角

iOS:如何显示 "Open With"应用程序切换器(操作系统选择器表)。没有文件,只有一个链接。

ios - locationServicesEnabled 只允许 iPhone 4?