Make TextField wrap it content in SwiftUI

百般思念 提交于 2020-12-06 06:39:55

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/61817927/make-textfield-wrap-it-content-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!