SwiftUI:如何将视图附加到多行文本的末尾?

3

当前

我有如下内容:

带有徽章的短文本:

enter image description here

目前它只是使用HStack简单完成的:

HStack {
    Text("Lorem ipsum dolor sit amet.")
        .font(.title2)
    Text("foo")
        .font(.system(size: 14, weight: .bold))
        .foregroundColor(.white)
        .padding(.horizontal, 4)
        .padding(.vertical, 2)
        .background(Color.red)
        .cornerRadius(5)
}

我的问题是,主文本是多行的,如果换行,它看起来像这样:

带有徽章的大型多行文本:

enter image description here

目标

但我的目标是,在主文本的最后一个单词之后始终显示foo徽章,应该长这样:

目标: 跟文本+文本一样的解决方案:

enter image description here

换句话说,我想要与SwiftUI的Text的串联功能相同的行为(Text() + Text()),但是由于徽章的格式,我不能使用它。像background()这样的格式修饰符会将返回类型更改为View,然后+运算符就不再起作用了。

实现我的目标最优雅的解决方案是什么?我希望不要使用UIKit。


可能这个 https://dev59.com/eVIH5IYBdhLWcg3wd-SX 的第二个答案会有帮助。 - ezaji
@ezaji 你是指第三个答案,自定义的AttributedText实现吗?第二个答案,我无法使用+运算符,因为背景和填充等内容会改变返回类型,就像我所描述的那样。 - Stitch
1
是的,第三个答案更适合您的目的。 - ezaji
1个回答

0

以下解决方案可以得到结果,但是徽章将位于行末。 如果是静态文本,您可以使用offset(x: )手动实现。

ZStack(alignment: .bottomTrailing) {
       Text("But my goal is that the foo badge is always displayed after the last word of the main text, which should look like this:")
           .font(.title2)

       Text("foo")
           .font(.system(size: 14, weight: .bold))
           .foregroundColor(.white)
           .padding(.horizontal, 4)
           .padding(.vertical, 2)
           .background(Color.red)
           .cornerRadius(5)
           .alignmentGuide(.bottom) { d in d[.bottom] }
           // .offset(x: 50)
}

很抱歉,这段文本是动态的,可能是从1到160个字符。 - Stitch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接