ios - SwiftUI TextField 减半

标签 ios swift swiftui

我是 Swift 编程的新手,我正在尝试通过一些 Youtube 教程学习如何构建我自己的聊天应用程序。我已经走了很远,但遇到了障碍。我不明白为什么当我尝试在 SwiftUI 中向上滚动此 View 时,消息会中途中断。我以为它与padding有关,但padding应该设置为all。查看下面的屏幕截图:

Swift text being cut off

我不确定我的代码哪里做错了,因为一切似乎都正常。我的代码附在下面。任何帮助将不胜感激!

import SwiftUI

struct ChatUIView: View {
    
    @State var message = ""
    //StateObject is the owner of the object...
    @StateObject var allMessages = Messages()
    
    var body: some View {
        VStack{
            
            ZStack{
                
                /*
                HStack{
                    Spacer()
                }*/
                
                VStack(spacing:5){
                    Text("Chat")
                        .fontWeight(.bold)
                }
                .foregroundColor(.white)
            }
            .padding(.all)
            
            //Spacer()
            VStack{
                
                //Spacer()
                //Displaying Message...
                
                ScrollView(.vertical, showsIndicators: false, content: {
                    
                    ScrollViewReader{reader in
                        
                        VStack(spacing: 20){
                            
                            ForEach(allMessages.messages){msg in
                                
                                //Chat Bubbles...
                                
                                ChatBubble(msg: msg)
                            
                                
                            }
                            //whenever new data is inserted, scroll to bottom...
                            .onChange(of: allMessages.messages) {(value) in
                                
                                //scrolling only user message...
                                
                                if value.last!.myMsg{
                                    reader.scrollTo(value.last?.id)
                                }
                                
                            }
                        }
                        .padding([.horizontal, .bottom])
                        .padding(.top, 25)
                    }
                })
                
                HStack(spacing:15){
                    
                    HStack(spacing: 15){
                        TextField("Message", text: self.$message)
                    }
                    .padding(.vertical, 12)
                    .padding(.horizontal)
                    .background(Color.black.opacity(0.06))
                    .clipShape(Capsule())
                    
                    
                    //send button
                    //hiding view...
                    if message != ""{
                        Button(action: {
                            
                            //appending message...
                            
                            //adding animation...
                            withAnimation(.easeIn){
                                allMessages.messages.append(Message(id: Date(), message: message, myMsg: false))
                            }
                            message = ""
                            
                        }, label: {
                            
                            Image("send")
                                .resizable()
                                .frame(width: 25, height: 25)
                                .rotationEffect(.init(degrees: 45))
                                .padding()
                                //.aspectRatio(contentMode: .fit)
                                //.font(.system(size: 0.5))
                                //.padding(.all)
                                .background(Color.black.opacity(0.07))
                                .clipShape(Circle())
                        })
                    }
                }
                .padding(.horizontal)
                .animation(.easeOut)
            }
            .padding(.bottom, UIApplication.shared.windows.first?.safeAreaInsets.bottom)
            .background(Color.white)
            .clipShape(RoundedShape())
        }
        //.edgesIgnoringSafeArea(.bottom)
        .background(Color.blue.edgesIgnoringSafeArea(.top))
    }
}

//Chat Bubbles...

struct ChatBubble : View {
    
    var msg : Message
    var body: some View{
        
        //Automatics scroll to bottom...
        //First assigning id to each row
        
        HStack(alignment: .top, spacing: 10){
            
            if msg.myMsg{
                
                //pushing msg to the left...
                
                //minimum space ...
                Spacer(minLength: 25)
                
                Text(msg.message)
                    .padding(.all)
                    .background(Color.black.opacity(0.06))
                    //.cornerRadius(15)
                    .clipShape(BubbleArrow(myMsg: msg.myMsg))
            } else {
                
                //pushing msg to the right...
                
                Text(msg.message)
                    .lineLimit(nil)
                    .foregroundColor(.white)
                    .padding(.all)
                    //.background(Color.black.opacity(0.06))
                    .background(Color.blue)
                    .clipShape(BubbleArrow(myMsg: msg.myMsg))
                
                Spacer(minLength: 25)
            }
        }
        .id(msg.id)
        //.padding(msg.myMsg ? .leading : .trailing, 55)
        //.padding(.vertical,10)
    }
}

// Bubble Arrow...

struct BubbleArrow : Shape {
    
    var myMsg : Bool
    
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: myMsg ? [.topLeft, .bottomLeft, .bottomRight] : [.topRight, .bottomLeft, .bottomRight], cornerRadii: CGSize(width: 10, height: 10))
        
        return Path(path.cgPath)
    }
}


// Custom Rounded Shape...

struct RoundedShape : Shape {
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 35, height: 35))
        
        return Path(path.cgPath)
    }
}

// Model Data For Message...

struct Message : Identifiable, Equatable {
    
    var id: Date
    var message: String
    var myMsg: Bool
    //var profilePic: String
    //var photo: Data?
    
}

class Messages: ObservableObject {
    
    @Published var messages : [Message] = []
    
    //sample data...
    init() {
        let strings = ["Hi!", "hello!", "How are you doing?!", "Fine, I just want to talk about life", "ok, I may be able to help with that", "This is awesome, thanks", "So what do you want to talk about?", "movies sound like a good topic. Let's start there!", "Ok, so tell me: What's you favorite movie?", "Definitely, interstellar for sure."]
        
        for i in 0..<strings.count{
            
            //simple logic for two sided message View...
            
            messages.append(Message(id: Date(), message: strings[i], myMsg: i % 2 == 0 ? false : true))
        }
    }
    
    func writeMessage(id: Date, msg: String, photo: Data?, myMsg: Bool){
        
        messages.append((Message(id: id, message: msg, myMsg: myMsg)))
        
        
    }
}

最佳答案

问题是在包含 ScrollView、TextField 和 Button 的 VStack 上使用 .clipShape(RoundedShape())。如果您注意到,不仅消息被减半,而且没有其他消息(还有一条)显示通过。自定义形状 RoundedShape 不够大,无法包含所有 View 。当我将其切换为内置形状矩形时,一切都会显示出来。我在 View 层次结构中看不到原因,但这就是问题所在。我会把它留给其他人来确定它发生了什么。

当您尝试调试 View 层次结构时,请从您的修饰符开始。将它们注释掉,直到发生变化,然后从那里开始探索。此外,修饰符的顺序很重要,因为在 View 上使用修饰符会给你一个全新的 View 。尝试一些简单的操作,比如将 .padding 放在 Text 上的 .font 之前,你会得到一个错误。这是因为填充 View 没有修改字体,即使修改后的 View 确实有字体。

关于ios - SwiftUI TextField 减半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65371684/

相关文章:

swift - 为什么 View 修饰符不能接受不可变变量?

javascript - iOS上的Cordova:应用程序在发送到后台之前没有音频

ios - 客户端获取iOS Universal Framework的版本号

Swift UIUserInterfaceIdiom 错误

.frame 的 SwiftUI 行为(高度 : nil)

ios - 来自 Storyboard 的 View 不会出现在 Xcode Preview 中

ios - Swift3 框架模块为空

ios - 从 xib 加载单元格时删除 UICollectionView 中的边框

ios - 下标 swift 2.2 使用不明确

swift - 图像未通过 POST 完整传输到服务器