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?