SwiftUI 父子 UI 组件之间通信 All In One
作者:互联网
SwiftUI 父子 UI 组件之间通信 All In One
demo
//
// SettingForm.swift
// BeiJingTourth
//
// Created by xgqfrms on 2022/5/16.
//
import SwiftUI
struct SettingForm: View {
@State private var noticeSwitch: Bool = false;
@State private var bgSwitch: Bool = false;
@State private var advancedSwitch: Bool = true;
var developer: String = "xgqfrms";
var version: String = "v1.0.0";
var date: String = "2022-01-01";
var logo: Bool;
init(_ logo: Bool) {
self.logo = logo;
}
var body: some View {
Form {
Section(header: Text("通用设置")) {
Toggle(isOn: $noticeSwitch) {
Text("开启消息通知")
}.onTapGesture {
// parent.updateLogo($noticeSwitch);
print("子组件,调用父组件中的方法")
}
Toggle(isOn: $advancedSwitch) {
Text("高级设置")
}
Toggle(isOn: $bgSwitch) {
Text("刷新背景")
}
}
Section(header: Text("通知设置")) {
if(noticeSwitch) {
Text("Twitter 通知开启✅")
Text("Google 通知开启✅")
Toggle(isOn: $noticeSwitch) {
Text("通知开启✅")
}
} else {
Text("Twitter 通知关闭❌")
Text("Google 通知关闭❌")
Toggle(isOn: $noticeSwitch) {
Text("通知关闭❌")
}
}
}
Section(header: Text("高级设置")) {
if(advancedSwitch) {
HStack{
HStack{
Image(systemName: "person")
Text("开发: ")
}
Spacer()
Text("\(developer)")
}
HStack{
HStack{
Image(systemName: "macwindow")
Text("版本: ")
}
Spacer()
Text("\(version)")
}
HStack{
HStack{
Image(systemName: "calendar")
Text("日前: ")
}
Spacer()
Text("\(date)")
}
} else {
Text("已关闭,请开启")
}
}
Section(header: Text("刷新背景设置")) {
if(bgSwitch) {
Text("刷新背景开启").task {
print("开启刷新背景✅")
}
} else {
Text("关闭").task {
print("关闭刷新背景❌")
}
}
}
}
}
}
//struct SettingForm_Previews: PreviewProvider {
// static var previews: some View {
// SettingForm()
// }
//}
//
// SettingView.swift
// BeiJingTourth
//
// Created by xgqfrms on 2022/5/13.
//
import SwiftUI
struct SettingView: View {
// background 切换 / logo 切换
@State private var defaultLogo: Bool = true;
// Cannot declare local wrapped variable in result builder
// TODO: 子组件,更新父组件中的属性状态,变量值 ???
func updateLogo(flag: Bool) -> Void {
// self.defaultLogo.toggle();
self.defaultLogo = flag;
}
// TODO: 子组件,调用父组件中的方法
var body: some View {
VStack(alignment: .center, spacing: 0) {
Image(defaultLogo ? "Beijing-Logo" : "Shanghai-Logo")
.resizable()
.scaledToFit()
.padding(.top)
.frame(width: 100, height: 100, alignment: .center)
.shadow(color: Color("ColorLight"), radius: 8, x: 0, y: 4)
//
Text("设置 ⚙️")
.font(.title)
.fontWeight(.bold)
.foregroundColor(Color("ColorBrownAdaptive"))
// Form
SettingForm(defaultLogo);
// SettingForm($defaultLogo);
// Cannot convert value '$defaultLogo' of type 'Binding<Bool>' to expected type 'Bool', use wrapped value instead
// Remove '$'
}
.padding()
.frame(maxWidth: 640)
}
}
struct SettingView_Previews: PreviewProvider {
static var previews: some View {
SettingView()
}
}
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载
标签:HStack,Bool,Text,defaultLogo,var,SwiftUI,组件,UI 来源: https://www.cnblogs.com/xgqfrms/p/16278964.html