0

I am trying to make a chat app, but having difficulties with the HStack. The border I have is going over the edge of the view so the full rounded rectangle isn't shown.

Text field

The code I have for the TextField and HStack is this.

var body: some View {
        HStack {
            CustomTextField(placeholder: Text("Enter your message"), text: $message)

            Button {
                messagesManager.sendMessage(message: message)
                message = ""
            } label: {
                Image(systemName: "arrow.up.circle.fill")
                    .foregroundColor(.blue)
                    .padding(10)
                    .scaledToFit()
            }
        }
        .padding(.horizontal)
        .padding(.vertical, 0)
        .border(.gray)
        .cornerRadius(20)
}

struct CustomTextField: View {
    var placeholder: Text
    @Binding var text: String
    var editingChanged: (Bool) -> () = {_ in}
    var commit: () -> () = {}
    
    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty {
                placeholder
                    .opacity(0.5)
            }
            TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
        }
    }
}

I can't find out how to reduce the length of the HStack so the whole of the rounded rectangle will show, as well as increasing the size of the button to fill up more space within the shape.

1
  • 1
    Actually your ordering for .padding(.horizontal) .padding(.vertical, 0) .border(.gray) .cornerRadius(20) is wrong . You should use padding after corner radius. Commented Oct 8, 2022 at 16:58

1 Answer 1

2

You can use overlay with RoundedRectangle for the border with a corner radius. I have added leading padding to your CustomTextField so that it will look proper and horizontal padding to your HStack after adding overlay.

var body: some View {
    HStack {
        CustomTextField(placeholder: Text("Enter your message"), text: $message)
            .padding(.leading, 10)
        
        
        Button {
            //messagesManager.sendMessage(message: message)
            message = ""
        } label: {
            Image(systemName: "arrow.up.circle.fill")
                .foregroundColor(.blue)
                .padding(10)
                .scaledToFit()
        }
    }
    .overlay(
        RoundedRectangle(cornerRadius: 20)
            .stroke(.gray)
    )
    .padding(.horizontal)
}

Preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.