最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ios - How to position SwiftUI view relative to other view - Stack Overflow

programmeradmin1浏览0评论

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)
    }
}

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

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)
    }
}

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

Share Improve this question asked Mar 18 at 14:28 Andrei HerfordAndrei Herford 18.8k24 gold badges108 silver badges258 bronze badges 1
  • Try using a hidden version of the smaller text on the left side, to give balance – Benzy Neez Commented Mar 18 at 15:19
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论