【问题标题】:Keep aspect ratio for UIbuttons background image保持 UIbuttons 背景图像的纵横比
【发布时间】:2016-11-10 14:14:24
【问题描述】:

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

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

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

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

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

我试过了

@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' 的初始化程序”

这让我很生气

【问题讨论】:

    标签: ios swift xcode uibutton


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      老问题,但由于我正在寻找相同的问题,我认为这仍然有效。

      我试图为backgroundImage 做同样的事情(正如大家所说),这是不可能的。但是,如果您的按钮仅包含一个图标,那么首先您应该使用setImage 方法,如果您正在使用它,您将可以访问按钮的imageView 属性。由于这是一个 UIImageView,您可以将 contentMode 设置为您喜欢的任何值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多