简体   繁体   中英

Programmatically Add Image Over a Button with Constraints (Swift)

It feels like I am missing something simple but I can't figure it out. I am trying to add an image over a button programmatically. In this case a Facebook logo over a custom button. I want the bottom to be over the left side of the button so I am anchoring the constraints of the image to the left side of the button.

However, I can't put a right constraint on the image because the size of the button is variable depending on the phone screen size (width set to a multiplier). I thought just setting the image content mode to aspect fit would take care of it, but what's happening is the image's right side is getting set based on its full size.

How can I handle this? I thought perhaps I could calculate the height of the button and use that to set the width of the image. I'm not sure about how to go about that and it also felt like I was missing a more elegant solution. Thanks!

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 

You can calculate logo's aspect ratio and use it combined with image's height

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

That way even if you resize the button, logo's width will resize as well at a correct ratio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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