UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: topAnchor = bottomAnchor?

Forums > iOS

So I'm laying out these components on the screen.

I add a UIView with an image, followed by a button.

I'm using autolayout, and set the button to be below the image, but it is aligning agains the top of the view.

Here's a code snippet:

let image = RexWalkingSilhouette(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
let button = MyButton("Start")

view.addSubview(image)
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
image.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    ...

    image.topAnchor.constraint(equalTo: subtitle.bottomAnchor, constant: 20),
    image.centerXAnchor.constraint(equalTo: subtitle.centerXAnchor),
    image.widthAnchor.constraint(equalTo: subtitle.widthAnchor),

    button.topAnchor.constraint(equalTo: image.bottomAnchor),
    button.centerXAnchor.constraint(equalTo: image.centerXAnchor),
    button.widthAnchor.constraint(equalToConstant: 100),
])

An here's an image (showing the views' bounds for clarity).

So what's wrong with my code. Why doesn't it align with the bottom anchor?

3      

I am not sure but I would remove the manual frame setting from the image and use AutoLayout for it as well.

3      

Doesn't seem to be the case. I just tested it.

3      

And what about image.bottomAnchor.constraint(equalTo: button.topAnchor), ? (I reversed the items)

3      

That puts the button above the image (also tested).

3      

Found out. I needed to set the view's height on autolayout. Even though I had already set the view's frame beforehand, which is strange.

image.heightAnchor.constraint(equalToConstant: 200),

3      

Yeah that was my suggestion but you said you tried that before ;)

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.