├── README.md └── TextFieldDynamicWidth.swift /README.md: -------------------------------------------------------------------------------- 1 | # TextFieldDynamicWidth 2 | 3 | SwiftUI TextField where the width is automatically made as small as possible. I used this in one of my projects and saw some people on Reddit were having trouble solving this problem. Just copy the TextFieldDynamicWidth.swift file to you project to use. 4 | 5 | ## Example 6 | 7 | ```swift 8 | HStack(spacing: 0) { 9 | TextFieldDynamicWidth(title: "Type something here!", text: $editingText) { editingChange in 10 | // logic 11 | } onCommit: { 12 | // logic 13 | }.font(.title).multilineTextAlignment(.center) 14 | Text("This text will appear immediately to the right of the text field") 15 | } 16 | ``` 17 | 18 | ## Notes 19 | 20 | I have 0 intention of maintaining this. I just wanted to help out those Redditors. If there is a problem or an improvement you want, make a pull request and I'll approve it. 21 | 22 | Reddit post: https://www.reddit.com/r/SwiftUI/comments/eq1a9o/how_to_make_textfielduitextfield_change_width_and/ 23 | -------------------------------------------------------------------------------- /TextFieldDynamicWidth.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TextFieldDynamicWidth.swift 3 | // 4 | // Created by Joseph Hinkle on 9/10/20. 5 | // 6 | 7 | import SwiftUI 8 | 9 | struct TextFieldDynamicWidth: View { 10 | let title: String 11 | @Binding var text: String 12 | let onEditingChanged: (Bool) -> Void 13 | let onCommit: () -> Void 14 | 15 | @State private var textRect = CGRect() 16 | 17 | var body: some View { 18 | ZStack { 19 | Text(text == "" ? title : text).background(GlobalGeometryGetter(rect: $textRect)).layoutPriority(1).opacity(0) 20 | HStack { 21 | TextField(title, text: $text, onEditingChanged: onEditingChanged, onCommit: onCommit) 22 | .frame(width: textRect.width) 23 | } 24 | } 25 | } 26 | } 27 | 28 | 29 | // 30 | // GlobalGeometryGetter 31 | // 32 | // source: https://stackoverflow.com/a/56729880/3902590 33 | // 34 | 35 | struct GlobalGeometryGetter: View { 36 | @Binding var rect: CGRect 37 | 38 | var body: some View { 39 | return GeometryReader { geometry in 40 | self.makeView(geometry: geometry) 41 | } 42 | } 43 | 44 | func makeView(geometry: GeometryProxy) -> some View { 45 | DispatchQueue.main.async { 46 | self.rect = geometry.frame(in: .global) 47 | } 48 | 49 | return Rectangle().fill(Color.clear) 50 | } 51 | } 52 | --------------------------------------------------------------------------------