简体   繁体   中英

Make TextField wrap it content in SwiftUI

I'm trying to implement such component

在此处输入图像描述

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.

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)

演示

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")
        }
    }
}

backup

You can make the framesize depending on your amount of characters in the TextField to achive what you want:

struct ContentView: View {
    @State private var textField = ""

    var body: some View {

        HStack {
            TextField("", text: $textField)
                .frame(width: CGFloat(textField.count+10)*5, height: nil)
                .textFieldStyle(RoundedBorderTextFieldStyle()) // Just to illustrate the field better.
                .multilineTextAlignment(.center)
            Text("PLN")
                .offset(x: -15, y:0)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM