Home > Enterprise >  Reduce width of HStack SwiftUI
Reduce width of HStack SwiftUI

Time:10-10

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.

CodePudding user response:

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

  • Related