Search code examples
iosswiftswiftui

Make TextField wrap it content in SwiftUI


I'm trying to implement such component

enter image description here

TextField (5 000) and Text (PLN) together should be centered horizontally. On entering new digit's, Text (PLN) should be dismissed. I think I have to combine this two views in to one container and center in, something like

HStack {
   TextField()
   Text("PLN")
}
.frame(alignment: .center)

But TextField is taking all possible width.

How could I handle it, or probably another solution.


Solution

  • Here is possible approach with dynamically sized TextField.

    Note: helper rectReader is taken from this my post.

    Tested with Xcode 11.4 / iOS 13.4 (black border is only for demo)

    demo

    struct DemoCenterTextField: View {
        @State private var value = ""
        @State private var frame = CGRect.zero
    
        var body: some View {
            return HStack(alignment: .bottom) {
                ZStack {
                    Text(self.value).foregroundColor(Color.clear)
                        .fixedSize()
                        .background(rectReader($frame))
    
                    TextField("#.#", text: $value)
                        .multilineTextAlignment(.trailing)
                        .frame(minWidth: 80, idealWidth: frame.width)
                        .fixedSize(horizontal: true, vertical: false)
                        .border(Color.black)      // << for demo only
    
                }.font(Font.system(size: 40).bold())
    
                Text("PLN")
            }
        }
    }