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

SwiftUI:如何将视图附加到多行文本的结尾? 现在的,swiftui,Swiftui,我有如下几点: 带徽章的短文本: HStack atm的操作非常简单: HStack { Text("Lorem ipsum dolor sit amet.") .font(.title2) Text("foo") .font(.system(size: 14, weight: .bold)) .foregroundColor(.white) .padding(.horizo

我有如下几点:

带徽章的短文本:

HStack atm的操作非常简单:

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)
}
我的问题是,主文本是多行的,如果它换行,它看起来像这样:

带有徽章的较大多行文字:

目标 但我的目标是,foo徽章始终显示在正文的最后一个字之后,应该如下所示:

目标:类似文本的解决方案+文本:

换句话说,我想要的行为与使用SwiftUI文本的连接功能一样(
Text()+Text()
),但由于徽章的格式问题,我无法使用。像
background()
这样的格式化修饰符将返回类型更改为
View
,然后
+
操作符不再工作


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

下面的解决方案给出了结果,但是,徽章将位于该行的末尾。 如果是静态文本,您可以使用
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)
}

下面的解决方案给出了结果,但徽章将位于该行的末尾。 如果是静态文本,您可以使用
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)
}

这可能会有所帮助。第二个答案。@ezaji您是说第三个答案,自定义AttributeText实现?第二个答案,我不能使用+运算符,因为背景和填充内容改变了返回类型,如我所述。是的,第三个答案更适合您的目的。这可能会有所帮助。第二个答案。@ezaji您是说第三个答案,自定义AttributeText实现?第二个答案,我不能使用+运算符,因为背景和填充内容改变了返回类型,如我所述。是的,第三个答案更适合您的目的。不幸的是,文本是动态的,可以是1到160个字符。幸运的是,文本是动态的,可以是1到160个字符