Home > database >  Need to create a chat bubble like Whatsapp with two labels on top of the message in SwiftUI
Need to create a chat bubble like Whatsapp with two labels on top of the message in SwiftUI

Time:07-16

I'm trying to create a chat bubble like this: enter image description here

        VStack(alignment: .leading) {
            // header
            HStack {
                Text(" 123456")
                    .bold()
                Spacer() // Spacer here!
                Text("~abcd")
            }
            .foregroundStyle(.secondary)
            
            // text
            Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!")
                .padding(.vertical, 5)
            
            // timestamp
            Text("12:00 PM")
                .frame(maxWidth: .infinity, alignment: .trailing)
            
        }
        .padding()
        .background(Color.gray.opacity(0.5))
        .cornerRadius(16)
        .frame(maxWidth: 250, alignment: .leading)
        
    }

CodePudding user response:

We can put that header into overlay of main text, so it will be always aligned by size of related view, and then it is safe to add spacer, `cause it do not push label wider than main text.

Tested with Xcode 13.4 / iOS 15.5

demo1demo2

var body: some View {
    let padding: CGFloat = 15
    ZStack {
        /// header
        VStack(alignment: .trailing) {
            /// text
            HStack {
                //Text("Hello Everyone")   // short test
                Text("Hello Everyone, bdhjewbdwebdjewbfguywegfuwyefuyewvfyeuwfvwbcvuwe!") // long test
            }
            .padding(.top, padding * 2)
            .overlay(
                HStack {            // << here !!
                    HStack() {
                        Text("abcd")

                    }
                    Spacer()
                    HStack {
                        Text("~abcd")
                    }
                }
            , alignment: .top)
            .padding([.trailing, .leading], padding)

            /// timestamp
            HStack(alignment: .center) {
                Text("12:00 PM")
            }.padding(.trailing, padding)

        }.background(Color.gray)
            .padding(.leading, padding)
            .frame(maxWidth: 250, alignment: .leading)
    }
}
  • Related