OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

SwiftUI - Mutable @FocusState for child view?

  • Thread starter Thread starter Kyle Horkley
  • Start date Start date
K

Kyle Horkley

Guest
I have a parent view with a @FocusState variable that I want to pass into a child view that contains a TextField. I want to be able to change the FocusState from within the child view, but I get the errors Cannot assign to property: 'self' is immutable and Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'.

Parent view:

Code:
struct ParentView: View {
    @State private var text: String
    @FocusState private var isEditing: Bool
    
    var body: some View {
        ChildView($text, $isEditing)
    }
}

struct ChildView: View {
    @Binding var text: String
    var isEditing: FocusState<Bool>.Binding
    
    init(_ text: Binding<String>, _ isEditing: FocusState<Bool>.Binding) {
        self._text = text
        self.isEditing = isEditing
    }
    
    var body: some View {
        TextField("Username", text: $text)
            .focused(isEditing)
        
        Button("Click me!") {
            isEditing = false  // Error here
        }
    }
}
<p>I have a parent view with a <code>@FocusState</code> variable that I want to pass into a child view that contains a <code>TextField</code>. I want to be able to change the <code>FocusState</code> from within the child view, but I get the errors <code>Cannot assign to property: 'self' is immutable</code> and <code>Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'</code>.</p>
<p>Parent view:</p>
<pre><code>struct ParentView: View {
@State private var text: String
@FocusState private var isEditing: Bool

var body: some View {
ChildView($text, $isEditing)
}
}

struct ChildView: View {
@Binding var text: String
var isEditing: FocusState<Bool>.Binding

init(_ text: Binding<String>, _ isEditing: FocusState<Bool>.Binding) {
self._text = text
self.isEditing = isEditing
}

var body: some View {
TextField("Username", text: $text)
.focused(isEditing)

Button("Click me!") {
isEditing = false // Error here
}
}
}
</code></pre>
Continue reading...
 

Latest posts

S
Replies
0
Views
1
Sarertt Pontampon
S
Top