Have you ever tried to do first baseline alignment using auto layout or stack view but been disappointed with the result? If yes, this post is for you.
What is Baseline?
In typography, the baseline is the imaginary line upon which a line of text rests. In most typefaces, the descenders on characters such as g or p extend down below the baseline while curved letters such as c or o extend ever-so-slightly below the baseline.
What is baseline alignment for?
We can use baseline for aligning texts with with different typefaces. In that case the final result looks much better than other forms of alignment.
But the more useful feature is baseline alignment of images and texts specially when the text is multiline. Suppose we have a horizontal stack view with an image and a label. Set the alignment of the stack view to first baseline and set the width and height constraints of the image view to 32.
What we will see is as below. The multiline sample is not bad but the single line version is awful.
What we wanted to see is this one.
What is the reason?
The reason is that custom images does not have baseline by default. Custom images are the images that we add to the assets comparing to system images. System images have baseline but we will talk about them in a minute. Now let’s focus just on custom images.
For your test run this code on a custom image.
let trashImage = UIImage(named: "trashImage") print(trashImage?.baselineOffsetFromBottom ?? "NA")
You will see that the value is nil, means there is no baseline by default. When threre is no baseline, the auto layout uses the top anchors of the elements to align them together in case of firstBaseline. To show that clearly I have signed some background color to the elements.
What is the solution?
Add baseline to your custom images programatically.
let trashImage = UIImage(named: "trashImage")?.withBaselineOffset(fromBottom: 13)
The result is what we expect. Now the baseline alignment works correctly.
Let’s see the final result. That’s it.
If you remember I explained that since the custom image does not have baseline, the auto layout engine ignores the baseline alignment you had requested and uses the top alignment. When you set the baseline offset to zero, the auto layout would be able apply the baseline alignment rule but the result of value zero might seem to you strange but it is completely normal. Zero value means the bottom of the image view. 😎
Positive values move baseline up and negative values move it down. That is weird but the truth. 🙄
In short, system images by nature have been created using typographic technics, so they that have baseline by default very similar to typefaces. Hence when you use system images you don’t have to set baseline. So easy.
- When you use custom images and first baseline or last baseline for alignment, set baseline offset to images.
- There is no need to do any thing about baseline for system images.