gpt4 book ai didi

SwiftUI:如何将 View 附加到多行文本的结尾?

转载 作者:行者123 更新时间:2023-12-05 06:56:31 26 4
gpt4 key购买 nike

当前

我有如下内容:

带徽章的短文本:

enter image description here

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

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

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

enter image description here

目标

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

目标:像文本+文本这样的解决方案:

enter image description here

换句话说,我想要的行为与使用 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)
}

关于SwiftUI:如何将 View 附加到多行文本的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65110371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com