SwiftUI聊天界面滚动时消息被截断问题求助
Hey there! I took a look at your code and spotted a couple of issues that are likely causing those messages to get cut off when you scroll up. Let's break down the fixes step by step:
1. Fix ScrollView & ScrollViewReader Nesting Order
Right now you have ScrollView wrapping ScrollViewReader, but the correct approach is to flip that order. ScrollViewReader needs to be the parent of ScrollView to properly control its scrolling behavior. This mismatch can lead to layout glitches like truncated content.
2. Ensure Long Messages Wrap Correctly
In your ChatBubble view, you only added .lineLimit(nil) to the non-user messages. User messages (where msg.myMsg is true) don't have this modifier, so long messages will get clipped instead of wrapping to multiple lines.
3. Give ScrollView Enough Vertical Space
Your ScrollView wasn't set to take up all available vertical space, which can cause content to get squeezed and truncated when scrolling. Adding .frame(maxHeight: .infinity) to the ScrollView ensures it fills the space between the header and input bar.
Modified Code Snippets
Here's how to update your code with these fixes:
Updated ChatUIView ScrollView Section
// Replace your existing ScrollView code with this ScrollViewReader { reader in ScrollView(.vertical, showsIndicators: false) { VStack(spacing: 20) { ForEach(allMessages.messages) { msg in ChatBubble(msg: msg) } .onChange(of: allMessages.messages) { value in if value.last!.myMsg { reader.scrollTo(value.last?.id) } } } .padding([.horizontal, .bottom]) .padding(.top, 25) } .frame(maxHeight: .infinity) // Add this to fill available space }
Updated ChatBubble View
struct ChatBubble : View { var msg : Message var body: some View{ HStack(alignment: .top, spacing: 10){ if msg.myMsg{ Spacer(minLength: 25) Text(msg.message) .lineLimit(nil) // Add this line .padding(.all) .background(Color.black.opacity(0.06)) .clipShape(BubbleArrow(myMsg: msg.myMsg)) } else{ Text(msg.message) .lineLimit(nil) .foregroundColor(.white) .padding(.all) .background(Color.blue) .clipShape(BubbleArrow(myMsg: msg.myMsg)) Spacer(minLength: 25) } } .id(msg.id) } }
Bonus: Minor Cleanup
You can also remove the commented-out Spacer() lines in your code to keep things tidy—they aren't needed anymore with the frame(maxHeight: .infinity) modifier on the ScrollView.
Give these changes a try, and your messages should no longer get truncated when scrolling up!
内容的提问来源于stack exchange,提问作者jeff-ridgeway

