In swiftUI, I want to have TextField
that when text is input, has the width relative to width of current content. I can achieve this by adding .fixedSize()
modifier. Problem is if I input too much text, width at some point will be bigger than screen size.
What I want to achieve is for TextField
to have size of content, until some maxWidth is reached, in this case scree width?
Edit: Thanks guys for swift :-) answers (I will give you upvotes), I have to mention that I have one additional request that makes a little difficult:
As you see I have TetxField
and then this text after it. I have written code, based on your answers, but could not get it just right:
struct ContentView: View {
@State var text: String
@State private var textField = ""
@State private var width: CGFloat = 10
var body: some View {
HStack(spacing: 0) {
GeometryReader { proxy in
TextField(text.isEmpty ? "Enter Text" : "", text: $text)
.truncationMode(.tail)
.frame(maxWidth: proxy.size.width)
.fixedSize()
}
Text(".package.com")
Spacer()
}
.frame(height: 24)
.padding([.leading, .trailing], 16)
}
}
You can do this without a geometry reader: https://www.magnuskahr.dk/posts/2023/05/swiftui-trailing-label-textfield/