【问题标题】:SwiftUI: ToggleStyle not working with @BindingSwiftUI:ToggleStyle 不适用于 @Binding
【发布时间】:2022-06-15 05:41:16
【问题描述】:

我正在尝试将 ToggleStyle 与自定义图标一起使用。单击切换没有任何反应,而如果我禁用 .toggleStyle 部分,一切正常。 你能帮帮我吗?

import SwiftUI

public struct IconToggle: View {
  let onIcon: Image
  let offIcon: Image
  @Binding var isOn: Bool

  public init(
    onIcon: Image,
    offIcon: Image,
    isOn: Binding<Bool>
  ) {
    self.onIcon = onIcon
    self.offIcon = offIcon
    self._isOn = isOn
  }

  public var body: some View {
    Toggle(isOn: $isOn) {
    }
      .toggleStyle(
        CheckboxStyle(
          onIcon: onIcon,
          offIcon: offIcon
        )
      )
  }
}


private struct CheckboxStyle: ToggleStyle {
  
  let onIcon: Image
  let offIcon: Image
  
  func makeBody(configuration: Configuration) -> some View {
    (configuration.isOn ? onIcon : offIcon)
      .resizable()
      .frame(width: 44, height: 44)
      .onTapGesture {
        configuration.isOn.toggle()
      }
  }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    我假设您想创建一个自定义 Toggle(),每次按下按钮时图像都会切换。您可以在下面尝试我的代码。代码有点不同,但逻辑是有的。

    import SwiftUI
    
    //copy paste all of these and test it out
    //just replace "apple" and "swift with your own image's name in the Assets Folder
    //when you call IconToggle() view, there is no extra parameter, so this code will instantly run in your xcode
    
    public struct IconToggle: View {
    
    @State var isOn = true
    
    public var body: some View {
        Toggle(isOn: $isOn) {
        }
        .toggleStyle(
            CheckboxStyle(
            isOn: $isOn
            )
        )
    }
    }
    
    private struct CheckboxStyle: ToggleStyle {
    
    @Binding var isOn: Bool
    
    func makeBody(configuration: Configuration) -> some View {
        Image(isOn ? "apple" : "swift") //custom images in my laptop
            .resizable()
            .frame(width: 44, height: 44)
            .onTapGesture {
                configuration.isOn.toggle()
            }
            .mask(Circle())
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多