iOS

Allow Swift UI to write RxSwift like rx.is Hidden

swiftui-hidden-modifier-en

Allow Swift UI to write RxSwift like rx.is Hidden

I want to be able to bind the display / non-display of Bool value and View!

I implemented the title, so I’ll leave it as a memo.
In RxSwift, you can write as follows.

private let booleanRelay = BehaviorRelay<Bool>(value: false)
// With RxSwift you can write below
booleanRelayText
    .bind(to: label.rx.isHidden)
    .disposed(by: disposeBag)
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

But in Swift UI you have to write it like this (please let me know if there is a different way to write it)

@State private var boolean = false
if boolean {
    Text("Hello world!")
}

I feel that this writing method has the following problems.

1. The nest becomes deeper.
2. The number of lines increases.
3. I can’t write declaratively.

So I tried to write as follows.

@State private var boolean = false
Text("Hello world!")
    .hidden(boolean)

Now you can show / hide Text according to the boolean value.

Implementation details

The above hidden is implemented as follows.

struct Hidden: ViewModifier {
   // Set the value from the parent View
    let hidden: Bool

    func body(content: Content) -> some View {
        VStack {
            if !hidden {
                content
            }
        }
    }
}

extension View {  
    func hidden(_ isHidden: Bool) -> some View {
        ModifiedContent(content: self, modifier: Hidden(hidden: isHidden))
    }
}

For the description of the first structure,

struct Hidden: ViewModifier {
    // Set the value from the parent View
    let hidden: Bool

    func body(content: Content) -> some View {
        if !hidden {
            content
        }
    }
}

I thought it would be okay to write, but I got an error saying Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type.
After a lot of trial and error, I got the above implementation. You may know if you follow the internal implementation, but honestly, I haven’t followed that much.
Is it because there is no View to return when hidden is false?

Summary

There are many cases where SwiftUI cannot be written as expected, so I would like to create an extension like this and deal with it well.
Also, I don’t really understand how to implement it, so I felt that I would like to deepen my understanding little by little.

 

0

COMMENT

Your email address will not be published. Required fields are marked *

CAPTCHA