Post

Replies

Boosts

Views

Activity

Reply to How to change SwiftUI TextField FocusState without having View refresh and cause a bounce effect
Some potential clarity since I cant edit the post My Problem: I want the user to be able to go from Textfield to TextField without the view bouncing as shown in the gif below. My Use Case: I have multiple TextFields and TextEditors in multiple child views. These TextFields are generated dynamically so I want the FocusState to be a separate concern. I made an example gif and code sample below which apple wont let me post a link to: https://imgur.com/a/X0KJa45 I think this is from the state change refresh. If it's not the refresh causing the bounce(as the user suggests in the comments) what is? Is there a way to stop this bounce while using FocusState?
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’21
Reply to How to change SwiftUI TextField FocusState without having View refresh and cause a bounce effect
Solution: It needs to be inside a ScrollView, List, GeometryReader, or some similar type of view Solution Code: struct MyObject: Identifiable, Equatable { public let id = UUID() public var name: String public var value: String } class MyObjViewModel: ObservableObject { @Published var myObjects: [MyObject] init(_ objects: [MyObject]) { myObjects = objects } } struct ContentView: View { @StateObject var viewModel = MyObjViewModel([ MyObject(name: "aa", value: "1"), MyObject(name: "bb", value: "2"), MyObject(name: "cc", value: "3"), MyObject(name: "dd", value: "4") ]) @State var focus: UUID? var body: some View { VStack { Form { Text("Header") ForEach($viewModel.myObjects) { $obj in FocusField(object: $obj, focus: $focus, nextFocus: { guard let index = viewModel.myObjects.map( { $0.id }).firstIndex(of: obj.id) else { return } focus = viewModel.myObjects.indices.contains(index + 1) ? viewModel.myObjects[index + 1].id : viewModel.myObjects[0].id }) } Text("Footer") } } } } struct FocusField: View { @Binding var object: MyObject @Binding var focus: UUID? var nextFocus: () -> Void @FocusState var isFocused: UUID? var body: some View { TextField("Test", text: $object.value) .onChange(of: focus, perform: { newValue in self.isFocused = newValue }) .focused(self.$isFocused, equals: object.id) .onSubmit { self.nextFocus() } } }
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’21