SwiftUI: HStack在ForEach中的VStack使多行文本重叠



我有一个文本()视图在HStack内部的ForEach内部的VStack。文本可以是任何长度的字符串,我无法控制它里面的内容。问题是,当您运行程序时,VStack中的视图重叠导致这种混乱的混乱

我想做的是有一个视图,根据多行文本视图的高度调整其高度,使视图永远不会重叠,并始终显示整个字符串。

下面是生成问题视图的代码:

struct ScrollingChatView: View {
@State var model: WatchModel
@State var messages: [DisplayableMessage] = []

var body: some View {
ScrollView {
if (!messages.isEmpty) {
LazyVStack {
ForEach(messages, id: .sortTimestamp) { message in
CompactChatView(message: message)
}
}.padding()
} else {
Text("Getting Chat...").padding()
}
}.onReceive(model.chatDriver.publisher) { m in
self.messages = m
}
}
}
struct CompactChatView: View {
@State var message: DisplayableMessage
@State var stringMessage: String? = nil
var body: some View {
VStack(alignment: .leading) {
HStack(alignment: .top) {
Text(message.displayAuthor)
.lineLimit(1)
.layoutPriority(1)
Group {
Text(getEmojiText(message))
.font(.headline)
.fixedSize(horizontal: false, vertical: true)
}
Spacer()
Text(message.displayTimestamp)
.font(.subheadline)
.foregroundColor(Color.gray)
.layoutPriority(1)
}.padding(.all, 6.0)
}
}
func getEmojiText(_ item: DisplayableMessage) -> String {
var fullMessage: String = ""
for m in item.displayMessage {
switch m {
case .text(let s):
fullMessage += s
case .emote(_):
print()
}
}
return fullMessage
}
}

我试过从文本视图中删除.fixedSize(horizontal: false, vertical: true),但它只使文本在一行后被截断,这不是我想要的。

如果您需要更多的上下文,整个项目位于:https://github.com/LiveTL/apple。我们正在查看macOS文件夹中的代码。

您可能会发现使用List()来代替尾随闭包是很有用的…

List(itemList) { item in 
Text(item)
}

这应该可以防止您在尝试显示消息时遇到的问题。有关列表的更多信息,请查看:https://developer.apple.com/documentation/swiftui/list.

你可以在25:11看到这个例子:https://developer.apple.com/videos/play/wwdc2019/216/

最新更新