Search code examples
swiftswiftuiswiftui-text

SwiftUi is there a way to get a Text inside a TextField


I have recently migrated from UIKit to SwiftUi 2.0 and I am rebuilding my app with SwiftUI . In UIKit I have a textbox and inside that textbox I have a post button and I am trying to do the same in SwiftUi but have not succeeded . In the image below for SwiftUi you can see that the Text is outside the TextField . This is the code I have for that region

      HStack {
                TextField("", text: $Postdata)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .frame(height: 38)
                        Text("Post")
                            .foregroundColor(.white)
                            .padding(.trailing, 10)
                    }

This is how it looks in UIKit

enter image description here

This is how I have it in SwiftUI, as you can see the post text is outside the TextField, any suggestions would be great

enter image description here


Solution

  • Using ZStack, we can arrange view in z axis. Spacer() is also doesn't block any view taping, dragging and etcetera like EmptyView(). It only provide space as the name itself.

     struct ContentView: View {
            @State var postdata = ""
            var body: some View {
                ZStack {
                    TextField("", text: $postdata)
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                        .frame(height: 38)
                    HStack {
                        Spacer()
                        Button(action: {
                            
                        }, label: {
                            Text("Post")
                                .bold()
                                .foregroundColor(.green)
                                .padding(.trailing, 10)
                        })
                    }
                }
            }
        }