1.自定義樣式
使用:
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Show Favorites Only")
}
.toggleStyle(MyToggleStyle())
ToggleStyle,可以根據(jù)該模板定制
struct MyToggleStyle:ToggleStyle {
let width: CGFloat = 50
let height:CGFloat = 30
var onColor:Color = .green
var offColor:Color = .init(UIColor.systemGray5)
var isAnimation = true
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.label
Spacer()
ZStack(alignment: configuration.isOn ? .trailing : .leading) {
Spacer()
RoundedRectangle(cornerRadius: width/2.0)
.frame(width: width, height: height)
.foregroundColor(configuration.isOn ? onColor : offColor)
RoundedRectangle(cornerRadius: (height-4)/2.0)
.frame(width: height-4 , height: height-4)
.padding(2)
.foregroundColor(.white)
.animation(isAnimation ? .easeIn(duration: 0.15) : nil)
.onTapGesture {
configuration.$isOn.wrappedValue.toggle()
}
}
}
}
}
條件判斷是否能點(diǎn)擊Toggle
@State var tmpState:Bool = false //臨時(shí)狀態(tài)
Toggle(isOn:$tmpState) {
Text("Click check..")
}
.onTapGesture {
print("inOn:\(tmpState) 檢查是否符合條件,如果不符合就還原狀態(tài)")
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+0.3) {
print("還原狀態(tài)")
withAnimation(Animation.easeIn(duration: 0.15)){
tmpState.toggle()
}
}
}
2.使用自定義樣式后,為Toggle添加onTapGesture無效的解決方法
由于SwiftUI的Gesture事件是先由子控件觸發(fā),所以可以使用simultaneousGesture ()修飾符告訴SwiftUI您希望父手勢和子手勢同時(shí)觸發(fā),如:
//替換原來得.onTapGesture
Toggle(isOn:$tmpState) {
Text("Click check..")
}
.toggleStyle(MyToggleStyle())//自定義樣式中使用了onTapGesture,所以需要.simultaneousGesture
.simultaneousGesture(
TapGesture()
.onEnded{
print("inOn:\(tmpState) 檢查是否符合條件,如果不符合就還原狀態(tài)")
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+0.3) {
print("還原狀態(tài)")
withAnimation(Animation.easeIn(duration: 0.15)){
tmpState.toggle()
}
}
}
)
//.simultaneousGesture可以使用多個(gè),如果有多個(gè).simultaneousGesture,則先執(zhí)行后添加的.simultaneousGesture