0

I have the following SwiftUI custom Toggle button:

struct TwoStateButton: View {
    @State var isSelected: Bool
    @State var isDisabled: Bool

    var onTap: ((Bool) -> Void)? = nil

    var body: some View {
        Toggle(isOn: $isSelected) {
            Image("buttonImage")
                .resizable()
                .frame(width: 50, height: 50)
                .padding(EdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4))
                .background(
                    Circle()
                        .fill(Color.clear)
                        .shadow(color: Color.black, radius: 50)
                        .frame(width: imageSize, height: imageSize)
                )
        }
        .disabled(isDisabled)
        .toggleStyle(.button)
        .onChange(of: isSelected) { value in
            if let onTap {
                onTap(value)
            }
        }
        .onChange(of: isEnabled) { value in
            print("\(isEnabled)")
        }
    }
}

And I want to be able to disable the button, this code is being called from UIKit in this way:

class MyView: UIView {
    private lazy var twoStateButton: TwoStateButton = {
        return TwoStateButton(isSelected: false, isDisabled: false)
    }()

    private lazy var toggleButton: UIView = {
        return UIHostingController(rootView: twoStateView).view
    }()

    init(frame: CGRect) {
        super.init(frame: frame)
    
        self.addSubview(toggleButton)
    }

    func updateView() {
        twoStateButton.isDisabled.toggle()

        print("twoStateButton.isDisabled=\(twoStateButton.isDisabled)"
    }
}

Every time the updateView is being called, the print below shows as:

twoStateButton.isDisabled=false

And the one inside .onChange(of: isSelected) never gets executed

How could I effectively disable the SwiftUI Toggle button?

3
  • You would need an ObservableObject with a Bool for toggling. SwiftUI views are value types and you can’t access their properties from a parent, especially State Commented Feb 27, 2024 at 23:04
  • I'm not too familiar with ObservableObject, especially with how to use it inside UIKit, could it be possible to show an example of it @loremipsum? Commented Feb 27, 2024 at 23:07
  • 1
    stackoverflow.com/questions/70435695/… Commented Feb 27, 2024 at 23:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.