iosswiftxcodeswiftui

How to position SwiftUI view relative to other view


I would like to position a Text view horizontally centered in a VStack (easy, since this is the default) and then show another Text on the right side next to the first view. The .firstTextBaseline alignment should stay intact.

VStack {
    HStack(alignment: .firstTextBaseline) {
        Text("Text")
            .font(largFont)
        Text("more")
            .font(smallFont)
    }
}

enter image description here

The automatic center alignment of the VStack is automatically applied to the complete HStack, thus to the combination of "Text" and "more".

How can I build the positioning where "Text" is centered and "more" next to it? While this can be done by using static (negative) paddings, offsets, etc. these solutions are not flexible when using different texts


Solution

  • I would put "more" as an overlay of "Text". Then you can control their relative positions by adjusting the alignmentGuide of "more" and the alignment: of the overlay.

    For example:

    Text("Text")
        .font(.largeTitle)
        .overlay(alignment: .trailingFirstTextBaseline) {
            Text("more")
                .font(.caption)
                .alignmentGuide(.trailing) { $0[.leading] }
        }
    

    The trailings and first text baselines of "more" are aligned, then we adjust what "trailing" means for "more", so that it means "leading" instead. Effectively, now the leading of "more" is aligned to the trailing of "Text".

    You can subtract some constant amount from $0[.leading] if you want to increase the spacing.


    This is sort of like the horizontal version of this question. Many of the answers there can also be used with simple adaptations. The above is basically the same idea as the second approach shown in this answer of mine.