【问题标题】:Programmatically Add Image Over a Button with Constraints (Swift)以编程方式在带有约束的按钮上添加图像 (Swift)
【发布时间】:2019-06-25 02:19:00
【问题描述】:

感觉好像我错过了一些简单的东西,但我无法弄清楚。我正在尝试以编程方式在按钮上添加图像。在这种情况下,自定义按钮上方的 Facebook 徽标。我希望底部位于按钮的左侧,因此我将图像的约束锚定到按钮的左侧。

但是,我不能对图像施加正确的约束,因为按钮的大小会根据手机屏幕大小(宽度设置为乘数)而变化。我认为只需将图像内容模式设置为宽高比就可以了,但是发生的情况是图像的右侧是根据其完整尺寸进行设置的。

我该如何处理?我想也许我可以计算按钮的高度并用它来设置图像的宽度。我不确定如何去做,而且我也觉得我错过了一个更优雅的解决方案。谢谢!

let customFacebookButton = UIButton(type: .system)

let facebookLogo: UIImageView = {
    let imageView = UIImageView(image: UIImage(named: "facebookLogo"))
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()

view.addSubview(facebookLogo)

facebookLogo.topAnchor.constraint(equalTo: customFacebookButton.topAnchor, constant: 10).isActive = true
facebookLogo.bottomAnchor.constraint(equalTo: customFacebookButton.bottomAnchor, constant: -10).isActive = true
facebookLogo.leadingAnchor.constraint(equalTo: customFacebookButton.leadingAnchor, constant: 10).isActive = true


// Custom Button Constraints in case it's helpful

customFacebookButton.topAnchor.constraint(equalTo: 
loginTextViewTitle.bottomAnchor, constant: 30).isActive = true
customFacebookButton.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
customFacebookButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
customFacebookButton.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor, multiplier: 0.8).isActive = true 

【问题讨论】:

  • 您能否解释或详细说明您希望如何放置 ImageView?它应该等于按钮的大小吗?
  • 因此图像将只是按钮左侧的方形徽标图像。只需一点额外的天赋,使按钮看起来更漂亮。试图模仿这个:cdn.dribbble.com/users/31796/screenshots/1358062/buttons.png
  • 对于正方形 mag_zbc 有正确的解决方案。看看他的回答。

标签: ios swift uibutton uiimage constraints


【解决方案1】:

您可以计算徽标的纵横比并将其与图像的高度结合使用

if let image = facebookLogo.image
{
    let ratio = image.size.width / image.size.height
    facebookLogo.widthAnchor.constraint(equalTo: facebookLogo.heightAnchor, multiplier: ratio).isActive = true
}

这样,即使您调整按钮的大小,徽标的宽度也会以正确的比例调整大小

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多