- Notifications
You must be signed in to change notification settings - Fork139
SwiftUI practices guidebook, written for humans.
NotificationsYou must be signed in to change notification settings
fzhlee/SwiftUI-Guide
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
更好的应用,更少的代码。
SwiftUI是一种创新、简单的iOS开发中的界面布局方案,可以通过Swift语言的强大功能,在所有的Apple平台上快速构建用户界面。 仅使用一组工具和API为任何Apple设备构建用户界面。
SwiftUI具有易于阅读和自然编写的声明式Swift语法,可与新的Xcode设计工具无缝协作,使您的代码和设计完美同步。
自动支持动态类型、暗黑模式、本地化和可访问性,意味着您的第一行SwiftUI代码已经是您编写过的最强大的UI代码了。
SwiftUI开发实用快捷键
Command + Option + Enter : 打开或关闭预览窗口
Command + Option + P : 刷新预览窗口
SwiftUI的231节教程及源码
所有课程的源码在Xcode 12.1正式版上编译通过。
1184节海量iOS开发课程,手把手学习iOS开发,App Store免费下载:
1、Xcode+SwiftUI互动教程免费下载地址:https://itunes.apple.com/cn/app/id1063100471
2、Swift语言入门实例互动教程免费下载地址:https://itunes.apple.com/cn/app/id1063100471
3、iOS开发中的神兵利器免费下载地址:https://itunes.apple.com/cn/app/id1063100471
4、Objective-C语言应用开发互动教程免费下载地址:https://apps.apple.com/cn/app/id1063100471
第一章: 常用的Views
- First Project
- Text-BasicStyle
- 3Text-Paragraph
- 4Text-Padding
- 5Text-FullScreen
- 6Text-DateFormatter
- 7Text-Append
- 8TextField
- 9TextField-SecureField
- 10Button
- 11Button-sheet
- 12Spacer
- 13Divider
- 14Image-Basic
- 15Image-Style
- 16Image-Processing
- 17Image-Blend
- 18Image-Mask
- 19Image-Transform
- 20Image-Web
- 21Picker
- 22PickerDate
- 23Slider
- 24Stepper
- 25Segment
- 26Toggle
- 27TabView
- 28Webview
- 29MapView
- 30Shape-Circle
- 31Shape-Rectangle
- 32Shape-Path
- 33GradientLinear
- 34GradientAngular
- 35GradientRadial
第二章: Animation动画
- 1scaleEffect+default
- 2Opacity+linear
- 3Offset+easeOut
- 4RotationEffect+spring
- 5CombinedAnimation
- 6SpeadAndDelay
- 7Repeating
- 8ToggleVisibility
- 9AsymmetricTransition
第三章: Gesture手势
- 1TapGesture+Single tap
- 2TapGesture+Double tap
- 3LongPressGesture
- 4RotationGesture
- 5DragGesture
- 6LongPressGestureAndDragGesture
第四章: Layout布局
- 1Group
- 2HSTack
- 3VSTack
- 4ZSTack
- 5List-Basic
- 6List-Insert
- 7List-Delete
- 8List-Move
- 9List-DeleteAndMove
- 10ScrollView-Vertical
- 11ScrollView-Horizontal
- 12ScrollView-VerticalAndHorizontal
- 13Form-Basic
- 14Form-Segment
- 15Form-EnableDisable
- 16Form-ShowHide
第五章: DataFlow数据流
- 1NavigationLink
- 2NavigationLinkAndGoBack
- 3PageNavigation
- 4ObjectBinding
- 5EnviromentObject
- 6Show_Modal
- 7Show-Alert
- 8Show-ActionSheet
第六章: More更多
- 1PreviewInNavigationView
- 2Background
- 3SizeCategory
- 4PreviewDevice
- 5ViewAsProperties
- 6onAppear-onDisappear
- 7ColorScheme-LightAndDark
- 8AnyView
- 9NavigationBarTitle
- 10NavigationItem
- 11ViewModifier
第七章: SwiftUI实战[共包含12个超炫的实例]
1、打开Xcode,然后使用菜单命令:File > New > Project命令,打开项目创建窗口。
2、在项目模板选择窗口中,选择Single View App模板,然后点击Next按钮,进入下一步设置窗口。
3、在项目配置窗口中,需要勾选Use SwiftUI复选框,然后填写其它的配置选项,点击Next按钮,完成项目的创建。
4、SwiftUI项目创建完成之后,其项目结构和代码功能如下图所示:
5、项目导航区:
| 文件名称 | 说明 |
|---|---|
| AppDelegate.swift | 提供didFinishLaunchingWithOptions等方法,用来处理程序启动之后的事件,或者响应来自外部的事件。 |
| SceneDelegate.swift | 设置应用程序窗口的rootViewController,并指定使用哪个ContentView作为rootViewController的rootView。 |
| ContentView.swift | 项目的初始界面,用户界面上的可视控件可以放置在此文件中。 |
| Assets.xcassets | 项目的资源文件,您可以在此处放置项目中所需的图片、颜色等资源。 |
| LaunchScreen.storyboard | 用来配置项目启动过程中所显示的内容。 |
| Info.plist | 项目的配置属性文件,配置产品名称、版本号、Build号、Bundle Identifier等项目。 |
6、代码编辑器:
- SwiftUI使用声明性语法,因此开发者可以简单地说明用户界面应该做什么。
- 例如,您可以编写需要包含文本字段的项目列表,然后描述每个字段的对齐方式,字体和颜色。
- 您的代码比以前更简单,更易于阅读,从而节省您的时间和维护。
7、ContentView.swift代码说明:
//导入SwiftUI框架import SwiftUI //定义一个名为ContentView的结构体,该结构体遵循View协议,遵循View协议的元素才可以在SwiftUI框架中。就像在UIKit中,所见皆UIView一样,在SwiftUI中,所见皆是View。structContentView:View{ //添加View协议中的body属性,在body属性中通过SwiftUI提供的各种布局控件,完成界面元素的搭建。关键词some表示返回的是某种View,但是SwiftUI不需要在意是具体的哪种Viewvarbody:someView{ //在屏幕上显示一个标签,标签的内容位于双引号之内Text("Hello World")}}//当处于Debug模式时,允许执行下方的代码#if DEBUG//定义一个遵循PreviewProvider的结构体,用于设置在右侧预览区需要实时预览的内容structContentView_Previews:PreviewProvider{//添加PreviewProvider协议中的previews属性,用来设置在实时预览区显示的内容staticvarpreviews:someView{ //设置在实时预览区显示ContentView结构体中的内容,您还可以在此设置预览的模拟器尺寸、是否Dark Mode等选项。ContentView()}}#endif
8、SceneDelegate.swift代码说明:
//使用此方法可以选择性地配置UIWindow窗口,并将其附加到提供的UIWindowScenefunc scene(_ scene:UIScene, willConnectTo session:UISceneSession, options connectionOptions:UIScene.ConnectionOptions){iflet windowScene= sceneas?UIWindowScene{ //初始化一个UIWindow窗口对象letwindow=UIWindow(windowScene: windowScene) // 使用一个UIHostingController实例,作为该窗口的根 view controller window.rootViewController=UIHostingController(rootView:ContentView()) // 将新建的窗口作为当前程序的窗口对象self.window= window // 将窗口作为主窗口并显示 window.makeKeyAndVisible()}}
示例代码:
VStack{ //Basic styleText("www.hdjc8.com").bold()Text("www.hdjc8.com").italic()Text("www.hdjc8.com").underline()Text("www.hdjc8.com").underline(true, color:.orange)Text("www.hdjc8.com").strikethrough()Text("www.hdjc8.com").strikethrough(true, color:.orange)Text("www.hdjc8.com").foregroundColor(Color.orange)Text("www.hdjc8.com").baselineOffset(CGFloat(5.0)).background(Color.orange)Text("www.hdjc8.com").background(Image("Picture"), alignment:.bottom) //FontVStack{Text("www.hdjc8.com").font(.footnote)Text("www.hdjc8.com").font(.system(size:36))Text("www.hdjc8.com").font(.system(.title, design:.monospaced))Text("www.hdjc8.com").font(.custom("BradleyHandITCTT-Bold", size:36))Text("www.hdjc8.com").fontWeight(Font.Weight.heavy)Text("www.hdjc8.com").fontWeight(Font.Weight.ultraLight)}}
示例代码:
VStack{Text("www.hdjc8.com")Text("www.hdjc8.com").tracking(10)Text("www.hdjc8.com").kerning(10)Text("www.hdjc8.com").blur(radius:1)Text("SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift.").lineSpacing(20)// .lineLimit(1).lineLimit(nil)Text("www.hdjc8.com").offset(x:40, y:0)Text("www.hdjc8.com").frame(width:200, height:80, alignment:.bottomTrailing).background(Color.orange)VStack{Text("www.hdjc8.com2").position(x:50, y:50).frame(width:300, height:100, alignment:.bottomTrailing).background(Color.orange)Text("Interactive\ntutorials\nfor\nXcode!").multilineTextAlignment(.center).lineLimit(4)Text("Hello\nInteractive Tutorials!").multilineTextAlignment(.leading)}}
示例代码:
VStack{Text("www.hdjc8.com").background(Color.black).foregroundColor(.white).padding(20)Text("www.hdjc8.com").padding().background(Color.black).foregroundColor(.white)Text("Swift User Interface").font(.largeTitle).foregroundColor(.black).padding(15).background(Color.yellow).padding(15).background(Color.orange).padding(10).background(Color.red)}
示例代码:
Text("Hello World").frame(minWidth:0, maxWidth:.infinity, minHeight:0, maxHeight:.infinity).background(Color.orange).font(.largeTitle).edgesIgnoringSafeArea(.all)
示例代码:
varnow=Date()staticletdateFormatter:DateFormatter={letformatter=DateFormatter()formatter.dateStyle=.longreturn formatter}()varbody:someView{Text("The time is:\(now, formatter:Self.dateFormatter)").font(.title).padding()}
示例代码:
Text("Interactive").foregroundColor(.yellow).fontWeight(.heavy)+ Text("tutorials").foregroundColor(.orange).strikethrough()+ Text("for").foregroundColor(.red).italic()+ Text("SwiftUI").foregroundColor(.purple).underline()
示例代码:
structContentView:View{@Statevarusername:String@Statevarnickname:Stringvarbody:someView{VStack{Text("Your username is\(username)!")Text("Your nickname is\(nickname)!")TextField("User Name", text: $username, onEditingChanged:{(value)inprint("onEditingChanged:\(self.username)")}){print("onCommit:\(self.username)")}.textFieldStyle(RoundedBorderTextFieldStyle())TextField("Nick Name", text: $nickname).textFieldStyle(RoundedBorderTextFieldStyle())}.padding()}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{ContentView(username:"", nickname:"")}}#endif
示例代码:
structContentView:View{@Statevarpassword:Stringvarbody:someView{VStack{Text("Your password is\(password)!")SecureField("Your password", text: $password){print("Your password is\(self.password)!")}.textFieldStyle(RoundedBorderTextFieldStyle())}.padding()}}
示例代码:
VStack{Button("First button"){print("---First button action.")}Button(action:{print("---Second button action.")}){Text("Second button")}Button(action:{print("---Third button action.")}){Image(systemName:"clock")Text("Third button")}.foregroundColor(Color.white).background(Color.orange) //padding for button : the tap area is wrongButton(action:{print("---padding for button.")}){Text("Default padding")}.padding().background(Color.yellow) //padding for label : the tap area is correct!Button(action:{print("---padding for label.")}){Text("Default padding").padding().background(Color.yellow)}Button(action:{print("---Button with image.")}){HStack{Image(systemName:"star")Text("Button with image")}.padding().background(Color.yellow)}Button(action:{print("---modifier button")}){Text("modifier button").modifier(MyButtonStyle())}}
示例代码:
structContentView:View{@StatevarisPresented=falsevarbody:someView{VStack{Button("Show modal"){self.isPresented=true}.sheet(isPresented: $isPresented, content:{MyDetailView(message:"Modal window")})}}}structMyDetailView:View{letmessage:Stringvarbody:someView{VStack{Text(message).font(.largeTitle)}}}
示例代码:
varbody:someView{VStack{HStack{Image(systemName:"clock")Spacer()}.padding()HStack{Image(systemName:"clock")Spacer()Text("\(Date())")}.padding()HStack{Image(systemName:"clock")Spacer(minLength:50)Text("\(Date())")}.padding()}}
示例代码:
VStack{VStack{Image(systemName:"clock")Divider()Text("\(Date())")}.padding()VStack{Image(systemName:"clock")Divider().background(Color.purple).scaleEffect(CGSize(width:1, height:10))Text("\(Date())")}.padding()}
示例代码:
VStack{Image("girlPicture")Image(systemName:"arkit").foregroundColor(.orange).font(.system(size:48))Image("girlPicture").resizable().aspectRatio(contentMode:.fit)}.padding()
示例代码:
ScrollView{VStack{Image("girlPicture").border(Color.orange)Image("girlPicture").border(Color.orange, width:10)Image("girlPicture").opacity(0.5)Image("girlPicture").shadow(radius:10)Image("girlPicture").shadow(color:.purple, radius:20, x:20, y:20)}}
示例代码:
ScrollView{VStack{Image("girlPicture")Image("girlPicture").blur(radius:CGFloat(2))Image("girlPicture").blur(radius:CGFloat(2), opaque:true)Image("girlPicture").brightness(0.2)Image("girlPicture").colorInvert()Image("girlPicture").colorMultiply(Color.yellow)Image("girlPicture").contrast(1.5)}VStack{Image("girlPicture").hueRotation(Angle.degrees(180))Image("girlPicture").saturation(10)Image("girlPicture").grayscale(5.5)Image("girlPicture").luminanceToAlpha()}}
示例代码:
VStack{Image("girlPicture").blendMode(.difference)ZStack{Image("texture")Image("girlPicture").blendMode(.multiply)}}.padding()
示例代码:
VStack{Image("girlPicture").clipShape(Circle())Image("girlPicture").mask(Circle())Image("texture").resizable().frame(width:300, height:300).mask(Text("SWIFT UI!").font(Font.system(size:64).bold()))}
示例代码:
ScrollView{VStack{Image("girlPicture").scaleEffect(0.8)Image("girlPicture").scaleEffect(CGSize(width:1.2, height:1))Image("girlPicture").scaleEffect(x:1.5, y:1, anchor:UnitPoint.bottomLeading)}VStack{Image("girlPicture").rotationEffect(Angle.init(degrees:90))Image("girlPicture").rotationEffect(Angle.init(degrees:30), anchor:UnitPoint.init(x:0, y:0))Image("girlPicture").rotation3DEffect(Angle.init(degrees:30), axis:(x:CGFloat(0.1), y:CGFloat(0.1), z:CGFloat(0)))}}
示例代码:
structContentView:View{@StateprivatevarremoteImage:UIImage?=nilletplaceholderOne=UIImage(named:"Picture")varbody:someView{Image(uiImage:self.remoteImage?? placeholderOne!).onAppear(perform: fetchRemoteImage)}func fetchRemoteImage(){guardlet url=URL(string:"http://hdjc8.com/images/logo.png")else{return}URLSession.shared.dataTask(with: url){(data, response, error)iniflet image=UIImage(data: data!){self.remoteImage= image}else{print(error??"")}}.resume()}}
示例代码:
structContentView:View{varfruits=["Apple","Banner","Pear","Watermelon"]varcolors=[Color.blue,Color.orange,Color.red,Color.purple]@StateprivatevarselectedItem=0varbody:someView{VStack{Picker(selection: $selectedItem, label:Text("Fruits")){ForEach(0..< fruits.count){Text(self.fruits[$0]).tag($0).foregroundColor(self.colors[$0])}}Text("Your choice:")+ Text("\(fruits[selectedItem])").foregroundColor(self.colors[selectedItem])}}}
示例代码:
structContentView:View{varmyDateFormatter:DateFormatter{letformatter=DateFormatter() formatter.dateStyle=.longreturn formatter}@StatevarselectedDate=Date()varbody:someView{VStack{DatePicker(selection: $selectedDate, displayedComponents:DatePickerComponents.hourAndMinute){Text("Date")}DatePicker(selection: $selectedDate, displayedComponents:DatePickerComponents.date){Text("Date")}DatePicker(selection: $selectedDate,in:Date()...Date().advanced(by:7*24*3600), displayedComponents:[.date,.hourAndMinute]){Text("Date")}Text("Your Choice:\(selectedDate, formatter: myDateFormatter)")}}}
示例代码:
structContentView:View{@Statevartemperature:Double=0varbody:someView{VStack{Slider(value: $temperature)Slider(value: $temperature, in:-20...40)Slider(value: $temperature, in:-20...40){(item)inprint(item)}HStack{Image(systemName:"sun.max")Slider(value: $temperature, in:-20...40, step:2){(item)inprint(item)}.accentColor(.pink).colorInvert()Image(systemName:"sun.max.fill")}.padding()Text("The temperature is\(Int(temperature)).")}}}
示例代码:
structContentView:View{@Statevartemperature:Double=0varbody:someView{VStack{Stepper(onIncrement:{self.temperature+=1}, onDecrement:{self.temperature-=1}, label:{Text("Temperature:\(Int(temperature))")})Stepper(onIncrement:{self.temperature+=1}, onDecrement:{self.temperature-=1}, onEditingChanged:{(item)inprint(item)}, label:{Text("Temperature:\(Int(temperature))")})}.padding()}}
示例代码:
structContentView:View{privatevaranimals=["🐶 Dog","🐯 Tiger","🐷 Pig"]varcolors=[Color.yellow,Color.orange,Color.red,Color.purple]@StateprivatevarselectedAnimal=0varbody:someView{VStack{Picker(selection: $selectedAnimal, label:Text("animals")){ForEach(0..< animals.count){Text(self.animals[$0]).tag($0)}}.pickerStyle(SegmentedPickerStyle())Text("Your choice:\(animals[selectedAnimal])")}}}
示例代码:
structContentView:View{@StatevarshowNotification=truevarbody:someView{VStack{Text("Show Notification:")+ Text("\(self.showNotification.description)").foregroundColor(.green).bold()Toggle(isOn: $showNotification){Text("Show notification:")}.padding()}}}
示例代码:
varbody:someView{TabView{Text("The home page.").font(.system(size:36)).tabItem({Image(systemName:"house")Text("Home")}).tag(0)Text("The settings page").font(.system(size:36)).tabItem({Image(systemName:"gear")Text("Settings")}).tag(1)}}
示例代码:
import SwiftUIimport WebKitstructContentView:UIViewRepresentable{func makeUIView(context:UIViewRepresentableContext<ContentView>)->WKWebView{returnWKWebView()}func updateUIView(_ uiView:WKWebView, context:UIViewRepresentableContext<ContentView>){letrequest=URLRequest(url:URL(string:"https://apple.com")!) uiView.load(request)}}
示例代码:
import SwiftUIimport MapKitstructContentView:UIViewRepresentable{func makeUIView(context:UIViewRepresentableContext<ContentView>)->MKMapView{returnMKMapView()}func updateUIView(_ uiView:MKMapView, context:UIViewRepresentableContext<ContentView>){ uiView.showsUserLocation=true uiView.mapType=MKMapType.satelliteletcoordinate2D=CLLocationCoordinate2D(latitude:39.915352, longitude:116.397105)letzoomLevel=0.02letregion=MKCoordinateRegion(center: coordinate2D, span:MKCoordinateSpan(latitudeDelta: zoomLevel, longitudeDelta: zoomLevel)) uiView.setRegion(uiView.regionThatFits(region), animated:true)}}
示例代码:
VStack{Circle()Circle().fill(Color.orange).frame(width:200, height:200)ZStack{Circle().fill(Color.purple)Circle().fill(Color.yellow).scaleEffect(0.8)Circle().fill(Color.orange).scaleEffect(0.6)}Rectangle()Rectangle().fill(Color.orange).frame(width:200, height:200)ZStack{Rectangle().fill(Color.purple).frame(width:300, height:200)Rectangle().fill(Color.yellow).frame(width:300, height:200).scaleEffect(0.8)Rectangle().fill(Color.orange).frame(width:300, height:200).scaleEffect(0.6)}}
示例代码:
VStack{Rectangle()Rectangle().fill(Color.orange).frame(width:200, height:200)ZStack{Rectangle().fill(Color.purple).frame(width:300, height:200)Rectangle().fill(Color.yellow).frame(width:300, height:200).scaleEffect(0.8)Rectangle().fill(Color.orange).frame(width:300, height:200).scaleEffect(0.6)}RoundedRectangle(cornerRadius:120)RoundedRectangle(cornerSize:CGSize(width:100, height:40)).frame(width:300, height:200)RoundedRectangle(cornerRadius:100, style:RoundedCornerStyle.continuous)}
示例代码:
Path{ pathin path.move(to:CGPoint(x:30, y:0)) path.addLine(to:CGPoint(x:30, y:200)) path.addLine(to:CGPoint(x:230, y:200)) path.addLine(to:CGPoint(x:230, y:0))}Path{ pathin path.addEllipse(in:CGRect(x:100, y:30, width:200, height:200)) path.addRoundedRect(in:CGRect(x:100, y:120, width:200, height:200), cornerSize:CGSize(width:10, height:10)) path.addEllipse(in:CGRect(x:100, y:210, width:200, height:200))}
示例代码:
Text("SwifUI Gradient").font(.system(size:36)).padding().foregroundColor(.white).background(LinearGradient(gradient:Gradient(colors:[.orange,.red,.purple]), startPoint:.topLeading, endPoint:.bottomTrailing))}
示例代码:
VStack{Text("SwifUI Gradient").font(.system(size:36)).padding().foregroundColor(.white).background(AngularGradient(gradient:Gradient(colors:[.orange,.red,.purple]), center:UnitPoint(x:0.5, y:0.5), angle:Angle.init(degrees:-45)))Text("SwifUI Gradient").font(.system(size:36)).padding().foregroundColor(.white).background(AngularGradient(gradient:Gradient(colors:[.orange,.red,.purple]), center:UnitPoint(x:0.5, y:0.5), startAngle:Angle.init(degrees:0), endAngle:Angle.init(degrees:0)))}
示例代码:
Text("SwifUI Gradient").font(.system(size:36)).padding().foregroundColor(.white).background(RadialGradient(gradient:Gradient(colors:[.orange,.red,.purple]), center:.init(x:0.5, y:0.5), startRadius:CGFloat(10), endRadius:CGFloat(120)))}
示例代码:
structContentView:View{@Statevarfactor:CGFloat=1varbody:someView{VStack{Image("logo").scaleEffect(factor)//设置Image的缩放比例为factor.animation(.default)//给Image添加default类型的动画效果Divider().fixedSize()Button(action:{self.factor+=0.2//当按钮点击时增加Image的缩放比例}){Text("Zoom in")}}}}
示例代码:
structContentView:View{@Statevarfactor:Double=1@Statevaralpha:Double=1varbody:someView{Image("logo").scaleEffect(CGFloat(factor)).opacity(alpha).onTapGesture{withAnimation(.linear(duration:1.0)){self.factor+=0.1self.alpha-=0.2}}}}
示例代码:
structContentView:View{@Statevardistance:Double=0varbody:someView{VStack{Image("logo").offset(x:0, y:CGFloat(distance)).animation(.easeOut(duration:2))Divider().fixedSize()Button(action:{self.distance-=120}){Text("Move Effect")}}}}
示例代码:
structContentView:View{@Statevarangle:Double=0varbody:someView{VStack{Image("logo").rotationEffect(Angle.init(degrees: angle)).animation(.spring())Divider().fixedSize()Button(action:{self.angle+=90}){Text("Rotation Effect")}}}}
示例代码:
structContentView:View{@Statevarradius:Double=0@Statevarbrightness:Double=0varbody:someView{VStack{Image("logo").shadow(radius:CGFloat(radius)).brightness(brightness).animation(.linear(duration:2))Divider().fixedSize()Button(action:{self.radius+=10self.brightness=1}){Text("Move Effect")}}}}
示例代码:
structContentView:View{@Statevarfactor:Double=1.0varanimation:Animation{Animation.linear(duration:1)// .speed(1)// .speed(5).delay(2)}varbody:someView{VStack{Image("logo").scaleEffect(CGFloat(factor)).animation(animation)Divider().fixedSize()Button(action:{self.factor+=0.2}){Text("Zoom In Effect")}}}}
示例代码:
structContentView:View{@Statevarangle:Double=0varanimation:Animation{Animation.spring().repeatForever()// .repeatForever(autoreverses: false)// .repeatCount(3)}varbody:someView{VStack{Image("logo").rotationEffect(Angle.init(degrees: angle)).animation(animation)Divider().fixedSize()Button(action:{self.angle+=45}){Text("Repeat Forever Effect")}}}}
示例代码:
structContentView:View{@StatevarshowingPassword=false@Statevarpassword=""varbody:someView{VStack{Toggle(isOn: $showingPassword.animation(.spring())){Text("Toggle Password")}if showingPassword{TextField("Password", text: $password).padding().border(Color.green, width:1)}}.padding()}}
示例代码:
structContentView:View{@StatevarshowPicture=falsevarbody:someView{VStack{Button(action:{withAnimation{self.showPicture.toggle()}}){Text("Show picture")}if showPicture{// Image("logo") // Image("logo")// .transition(.move(edge: .top)) // Image("logo")// .transition(.scale(scale: 0)) // Image("logo")// .transition(.slide) // Image("logo")// .transition(.asymmetric(insertion: .scale(scale: 0), removal: .slide))Image("logo").transition(AnyTransition.scale(scale:0).combined(with:.slide))}}}}
示例代码:
structContentView:View{@StatevarisPressed=falsevarbody:someView{lettapGesture=TapGesture().onEnded{ _inself.isPressed.toggle()}returnCircle().fill(Color.orange).frame(width:240, height:240).gesture(tapGesture).scaleEffect(isPressed?1.4:1).animation(.default)}}
示例代码:
structContentView:View{@StatevarisPressed=falsevarbody:someView{returnCircle().fill(Color.orange).frame(width:240, height:240).scaleEffect(isPressed?1.4:1).animation(.default).onTapGesture(count:2){self.isPressed.toggle()print("Double tap.")}}}
示例代码:
structContentView:View{@GestureStatevarisLongPressed=falsevarbody:someView{letlongPressGesture=LongPressGesture().updating($isLongPressed){ value, state, transcationinprint(value, state, transcation) state= value}.onEnded{(value)inprint(value)}returnCircle().fill(Color.orange).frame(width:240, height:240).gesture(longPressGesture).scaleEffect(isLongPressed?1.4:1).animation(.default)}}
示例代码:
structContentView:View{@Statevarangle=0.0varbody:someView{letrotationGesture=RotationGesture(minimumAngleDelta:Angle.init(degrees:20)).onChanged({(angle)inself.angle+= angle.animatableData}).onEnded{(angle)inprint(self.angle)}returnImage("logo").gesture(rotationGesture).rotationEffect(Angle.init(degrees:self.angle))}}
示例代码:
structContentView:View{@Statevaroffset:CGSize=.zerovarbody:someView{letdragGesture=DragGesture().onChanged{(value)inprint(value.startLocation, value.location, value.translation)self.offset= value.translation}.onEnded{(value)inif(abs(value.translation.width)>=40 ||abs(value.translation.height-(-260))>=40){self.offset=.zero}else{self.offset=CGSize(width:0, height:-260)}}returnVStack{Circle().fill(Color.black).opacity(0.1).frame(width:200, height:200).offset(CGSize(width:0, height:-50))Circle().fill(Color.orange).frame(width:200, height:200).offset(offset).gesture(dragGesture).animation(.spring())}}}
示例代码:
structContentView:View{@Statevaroffset:CGSize=.zero@GestureStatevarisLongPressed=falsevarbody:someView{letlongPressGesture=LongPressGesture().updating($isLongPressed){ value, state, transcationinprint(value, state, transcation) state= value}.onEnded{(value)inprint(value)}letdragGesture=DragGesture().onChanged{(value)inprint(value.startLocation, value.location, value.translation)self.offset= value.translation}.onEnded{(value)inif(abs(value.translation.width)>=40 ||abs(value.translation.height-(-260))>=40){self.offset=.zero}else{self.offset=CGSize(width:0, height:-260)}}.simultaneously(with: longPressGesture)returnVStack{Circle().fill(Color.black).opacity(0.1).frame(width:200, height:200).offset(CGSize(width:0, height:-50))Circle().fill(Color.orange).frame(width:200, height:200).offset(offset).gesture(dragGesture).scaleEffect(isLongPressed?1.4:1).animation(.spring())}}}
示例代码:
structContentView:View{varbody:someView{Group{Text("Apple")Text("Banana")Text("Orange")Text("Watermelon")Text("Grape")Text("Papaya")Text("Pear")}.font(.title).foregroundColor(.orange).padding()}}
示例代码:
structContentView:View{varbody:someView{HStack(alignment:.bottom, spacing:40){Image(systemName:"book.fill")Text("Interactive Tutorials")Spacer()Image(systemName:"icloud.and.arrow.down")}.padding()}}
示例代码:
structContentView:View{varbody:someView{VStack{Text("The fruit and the tree").font(.largeTitle)Image("Apple")Text("An apple is a sweet, edible fruit produced by an apple tree Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus.").font(.body).lineLimit(nil).frame(height:200)}.padding()}}
示例代码:
structContentView:View{varbody:someView{ZStack(alignment:.center){Image("beach").clipShape(Circle())Text("Sea beach").font(.system(size:48)).foregroundColor(.white)Text("Hawaii - USA").font(.system(size:14)).foregroundColor(.white).offset(x:0, y:36)}.padding(10)}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{List{Text("Objective-C")Text("Swift")Text("Flutter")} // List(0..<5) { item in// Text("Item : \(item)")// } // ForEach(languages, id: \.self) { language in// Text(language)// }}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{NavigationView{List{ForEach(languages, id:\.self){ languageinText(language)}.onInsert(of:["demo"], perform:{(offset, message)inprint(offset)})}.navigationBarTitle(Text("Edit Row"), displayMode:.large).navigationBarItems(trailing:EditButton())}.padding()}func insertItem(to offsets:Int, message:[NSItemProvider]){ languages.insert(message[0].description, at: offsets)}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{NavigationView{List{ForEach(languages,id: \.self){ languageinText(language)}.onDelete(perform: delete)}.navigationBarItems(trailing:EditButton())}}func delete(at offsets:IndexSet){iflet first= offsets.first{ languages.remove(at: first)}}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{NavigationView{List{ForEach(languages,id: \.self){ languageinText(language)}.onMove{(source, destination)inself.languages.move(fromOffsets: source, toOffset: destination)}}.navigationBarTitle(Text("Edit Row"), displayMode:.large).navigationBarItems(trailing:EditButton())}}func moveItem(from source:IndexSet, to destination:Int){ languages.move(fromOffsets: source, toOffset: destination)print(languages)}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{NavigationView{List{ForEach(languages, id: \.self){ languageinText(language)}.onDelete(perform: deleteItem).onMove(perform: moveItem)}.navigationBarTitle(Text("Edit Row"), displayMode:.large).navigationBarItems(trailing:EditButton())}}func deleteItem(at offsets:IndexSet){iflet first= offsets.first{ languages.remove(at: first)}}func moveItem(from source:IndexSet, to destination:Int){ languages.move(fromOffsets: source, toOffset: destination)}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{ScrollView(.vertical, showsIndicators:false){VStack(alignment:HorizontalAlignment.leading, spacing:20){Text("Overview").font(.system(size:48)).padding(10)Text("With the power of Xcode, the ease of Swift, and the revolutionary features of cutting-edge Apple technologies, you have the freedom to create your most innovative apps ever.\nSwiftUI provides views, controls, and layout structures for declaring your app's user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app's models down to the views and controls that users will see and interact with.").lineLimit(nil).frame(width:300, height:240, alignment:.topLeading).padding(10)Image("iPhone").resizable().frame(width:300, height:556, alignment:.center)}}.background(Color.orange).padding(10).navigationBarTitle(Text("ScrollView"))}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{ScrollView(.horizontal, showsIndicators:true){HStack(alignment:.center, spacing:20){Image("iPhone").resizable().frame(width:300, height:556, alignment:.center)Image("iPhoneSerial").resizable().frame(width:823, height:556, alignment:.center)Image("iPhone").resizable().frame(width:300, height:556, alignment:.center)}}.background(Color.orange).padding(10)}}
示例代码:
structContentView:View{@Statevarlanguages=["Objective-C","Swift","Flutter"]varbody:someView{ScrollView(.vertical, showsIndicators:false){VStack(alignment:HorizontalAlignment.leading, spacing:20){Text("Overview").font(.system(size:48)).padding(10)Text("With the power of Xcode, the ease of Swift, and the revolutionary features of cutting-edge Apple technologies, you have the freedom to create your most innovative apps ever.\nSwiftUI provides views, controls, and layout structures for declaring your app's user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app's models down to the views and controls that users will see and interact with.").lineLimit(nil).frame(width:300, height:350, alignment:.topLeading).padding(10)ScrollView(.horizontal, showsIndicators:true){HStack(alignment:.center, spacing:20){Image("iPhone").resizable().frame(width:189, height:350, alignment:.center)Image("iPhoneSerial").resizable().frame(width:518, height:350, alignment:.center)Image("iPhone").resizable().frame(width:189, height:350, alignment:.center)}}.background(Color.orange).padding(10)}}.background(Color.orange).padding(10).navigationBarTitle(Text("ScrollView"))}}
示例代码:
structContentView:View{privatevarlanguages=["Swift","Objective-C"]@StateprivatevarselectedLanguage=0@StatevarworkingYear:Double=2@StatevarenableNotification=falsevarbody:someView{NavigationView{Form{Picker(selection: $selectedLanguage, label:Text("Languages")){ForEach(0..< languages.count){Text(self.languages[$0]).tag($0)}}.pickerStyle(SegmentedPickerStyle())HStack{Text("Working years")Slider(value: $workingYear, in:1...10, step:1)}Toggle(isOn: $enableNotification){Text("Enable Notification")}Button(action:{print("Your programming language:\(self.languages[self.selectedLanguage])")print("Your working years:\(Int(self.workingYear))")print("Enable notification:\(self.enableNotification)")}){Text("Submit")}}.navigationBarTitle(Text("Profiles"))}}}
示例代码:
structContentView:View{privatevarlanguages=["Swift","Objective-C"]@StateprivatevarselectedLanguage=0@StatevarworkingYear:Double=2@StatevarenableNotification=falsevarbody:someView{NavigationView{Form{Section(header:Text("Please enter your information:"), footer:Text("Note: Enabling notification to get more infomration")){Picker(selection: $selectedLanguage, label:Text("Languages")){ForEach(0..< languages.count){Text(self.languages[$0]).tag($0)}}.pickerStyle(SegmentedPickerStyle())HStack{Text("Working years")Slider(value: $workingYear, in:1...10, step:1)}Toggle(isOn: $enableNotification){Text("Enable Notification")}}Button(action:{ // activate theme!print("Your programming language:\(self.languages[self.selectedLanguage])")print("Your working years:\(Int(self.workingYear))")print("Enable notification:\(self.enableNotification)")}){Text("Submit")}}.navigationBarTitle(Text("Profiles"))}}}
示例代码:
structContentView:View{@StatevarenableForm=false@StatevarenableNotification=false@StatevaruserName=""@Statevarpassword=""varbody:someView{NavigationView{Form{Toggle(isOn: $enableForm){Text("Enable Form")}Section(header:Text("Please enter your information:")){TextField("Username", text: $userName)SecureField("Password", text: $password)Toggle(isOn: $enableNotification){Text("Enable Notification")}}.disabled(enableForm)}.navigationBarTitle(Text("Profiles"))}}}
示例代码:
structContentView:View{@StatevarshowingVisible=false@StatevaruserName=""@Statevarpassword=""varbody:someView{NavigationView{Form{Toggle(isOn: $showingVisible.animation()){if(showingVisible){Text("Hide Form")}else{Text("Show Form")}}if(showingVisible){Section(header:Text("Please enter your information:")){TextField("Username", text: $userName)SecureField("Password", text: $password)}}}.navigationBarTitle(Text("Profiles"))}}}
示例代码:
structContentView:View{@StatevarisPresented=falsevarbody:someView{// NavigationView {// HStack{// NavigationLink(destination: Text("Detail Page #1") ) {// Text("Go detail Page #1 >")// }// .navigationBarTitle("Index Page #1")// .accentColor(Color.orange)// }// }NavigationView{HStack{NavigationLink(destination:MyDetailView(message:"Detail Page #2")){Text("Go detail Page #2 >")}.navigationBarTitle("Index Page #1")}}}}structMyDetailView:View{letmessage:Stringvarbody:someView{VStack{Text(message).font(.largeTitle)}}}
示例代码:
structContentView:View{@StateprivatevarisPresented=falsevarbody:someView{ // NavigationView{// VStack{// Image("Picture").onTapGesture {// self.isPresented.toggle()// print(self.isPresented)// }// NavigationLink(destination: Text("< Go back").onTapGesture {// self.isPresented.toggle()// }, isActive: $isPresented) {// Text("ddd")// }// }NavigationView{VStack{NavigationLink(destination:DetailView(preView:self), isActive: $isPresented){Image("logo").renderingMode(.original)Text("Next Page >")}}}}func toggleValue(){self.isPresented.toggle()}}
示例代码:
import SwiftUIstructInfoModel:Hashable{vardescription:StringvarpictureName:String}structContentView:View{varmessages:[InfoModel]varbody:someView{returnNavigationView{List{ForEach(messages, id: \.self){ messageinNavigationLink(destination:DetailView(imageName: message.pictureName)){Text(message.description)}}}.navigationBarTitle("Picture List")}}}structDetailView:View{varimageName:Stringvarbody:someView{Image(imageName)}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{letmodel1=InfoModel(description:"A lady with a horse", pictureName:"Picture1")letmodel2=InfoModel(description:"An African animal with a very long neck", pictureName:"Picture2")returnContentView(messages:[model1, model2])}}#endif
示例代码:
classUserModel:ObservableObject{@PublishedvarnickName:String=""}structContentView:View{@ObservedObjectvarmodel=UserModel()@StatevarisPresented=falseletdismiss=Alert.Button.default(Text("OK")){}varalert:Alert{Alert(title:Text("Your nickname"), message:Text("\(self.model.nickName)"), dismissButton: dismiss)}varbody:someView{VStack{TextField("Your nickname", text: $model.nickName).padding()Button(action:{self.isPresented=true}){Text("Show")}.alert(isPresented: $isPresented){()->Alertin alert}}}}
示例代码:
import SwiftUIclassUserModel:ObservableObject{@PublishedvarnickName:String=""}structContentView:View{@EnvironmentObjectvarmodel:UserModel@StatevarisPresented=falsevarbody:someView{NavigationView{VStack{TextField("Your nickname", text: $model.nickName).padding()NavigationLink(destination:DetailView()){Text("Show Detail")}}}}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{letmodel=UserModel() model.nickName="Super man"returnContentView().environmentObject(model)}}#endif
示例代码:
structContentView:View{@StatevarisPresented=falsevarmodalView:someView{Text("The Modal View").font(.system(size:48)).bold()}varbody:someView{Button("Show Modal View"){self.isPresented=true}.sheet(isPresented: $isPresented, content:{self.modalView})}}
示例代码:
structContentView:View{@StatevarisAlert=falseletprimaryButton=Alert.Button.default(Text("Yes")){print("Yes, I'm a student.")}letsecondaryButton=Alert.Button.destructive(Text("No")){print("No, I'm not a student.")}varalert:Alert{Alert(title:Text("Question"), message:Text("Are you a student?"), primaryButton: primaryButton, secondaryButton: secondaryButton)}varbody:someView{VStack{Button("Alert Sheet"){self.isAlert=true}}.alert(isPresented: $isAlert, content:{ alert})}}
示例代码:
structContentView:View{@StatevarisPresented=falsevarmyActionSheet:ActionSheet{ActionSheet(title:Text("Information"), message:Text("What's your favorite?"), buttons:[.default(Text("Fishing")){print("---I like fishing")},.destructive(Text("Hunting")){print("---I like hunting")},.cancel({print("---Nothing")})])}varbody:someView{VStack{Button("Show action sheet"){self.isPresented=true}}.actionSheet(isPresented: $isPresented, content:{ myActionSheet})}}
示例代码:
structContentView:View{varbody:someView{VStack{Image("SwiftUI").navigationBarTitle("About SwiftUI")Text("SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. With a declarative Swift syntax that’s easy to read and natural to write, SwiftUI works seamlessly with new Xcode design tools to keep your code and design perfectly in sync. Automatic support for Dynamic Type, Dark Mode, localization, and accessibility means your first line of SwiftUI code is already the most powerful UI code you’ve ever written.").padding()}}}
示例代码:
structContentView:View{varbody:someView{VStack{Spacer()Text("SwiftUI Tutorials").font(.largeTitle).padding().background(Color.orange)Spacer()Text("SwiftUI Tutorials").font(.largeTitle).padding().background(Image("iPhoneSerial").resizable())Spacer()Text("SwiftUI Tutorials").font(.largeTitle).padding().background(Circle().fill(Color.orange).frame(width:280, height:280))Spacer()}}}
示例代码:
structContentView:View{varbody:someView{VStack{Text("Dynamic Type sizes").font(.system(size:36))Text("Dynamic Type sizes")}}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{VStack{Spacer()ContentView().environment(\.sizeCategory,.extraSmall)Spacer()ContentView()Spacer()ContentView().environment(\.sizeCategory,.accessibilityExtraExtraExtraLarge)Spacer()}}}#endif
示例代码:
structContentView:View{varbody:someView{VStack{Text("Dynamic Type sizes").font(.system(size:48))Text("Dynamic Type sizes")}}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{Group{ContentView().previewDevice(PreviewDevice(rawValue:"iPhone 8")).previewDisplayName("Device-8")ContentView().previewDevice(PreviewDevice(rawValue:"iPhone XS Max")).previewDisplayName("Device-XS Max")}}}#endif
示例代码:
structContentView:View{leticon=Image(systemName:"book.fill")lettitle=Text("Interactive Tutorials")letflag=Image(systemName:"icloud.and.arrow.down")varbody:someView{HStack(alignment:.bottom, spacing:40){ icon titleSpacer() flag}.padding()}}
示例代码:
structDetailView:View{varbody:someView{Text("Detail").onAppear{print("DetailView appeared!")}.onDisappear{print("DetailView disappeared!")}}}structContentView:View{@StateprivatevarisPresented=falsevarbody:someView{Text("Show Detail >").sheet(isPresented: $isPresented, content:{DetailView()}).onTapGesture{self.isPresented=true}.onDisappear{print("ContentView disappeared!")}.onAppear{print("ContentView appeared!")}}}
示例代码:
structContentView:View{varbody:someView{VStack(alignment:.center, spacing:20){Text("Dynamic Type sizes").font(.system(size:48)).foregroundColor(Color.secondary)Text("Dynamic Type sizes").foregroundColor(Color.accentColor)Image(systemName:"star.fill").foregroundColor(Color.secondary).font(.system(size:64))}.frame(minWidth:0, maxWidth:.infinity, minHeight:0, maxHeight:.infinity).background(Color.primary).edgesIgnoringSafeArea(.all)}}#if DEBUGstructContentView_Previews:PreviewProvider{staticvarpreviews:someView{HStack{ContentView().environment(\.colorScheme,.light)ContentView().environment(\.colorScheme,.dark)}}}#endif
示例代码:
structContentView:View{privatevarrandomBool=Bool.random() // var body: some View {// Group {// if randomBool {// Text("Hi, you get the gift.")// .font(.system(size: 32))// } else {// Text("Sorry, you miss the gift.")// .font(.system(size: 32))// }// }// } // var body: some View {// if randomBool {// return Text("Hi, you get the gift.")// .font(.system(size: 32))// } else {// return Text("Sorry, you miss the gift.")// .font(.system(size: 32))// }// }varbody:AnyView{if randomBool{returnAnyView(Image(systemName:"star.fill").font(.system(size:72)))}else{returnAnyView(Text("Sorry, you miss the gift.").font(.system(size:32)))}}}
示例代码:
structContentView:View{varbody:someView{NavigationView{ // Text("SwiftUI's NavigationView") // Text("SwiftUI's NavigationView")// .navigationBarTitle(Text("SwiftUI")) // Text("SwiftUI's NavigationView")// .navigationBarTitle(Text("SwiftUI"), displayMode: .large)Text("SwiftUI's NavigationView").navigationBarTitle(Text("SwiftUI"), displayMode:.inline)}}}
示例代码:
structTrailingButtons:View{varbody:someView{HStack{Button(action:{print("Download the data")}){Image(systemName:"icloud.and.arrow.down.fill")}Button(action:{print("Edit the data")}){Image(systemName:"pencil.tip.crop.circle")}}}}structContentView:View{varbody:someView{NavigationView{Text("SwiftUI's NavigationView").navigationBarTitle(Text("SwiftUI")).navigationBarItems(leading:Button(action:{print("Go to index page")}){Text("Index")}, trailing:TrailingButtons())}}}
示例代码:
structContentView:View{varbody:someView{VStack(alignment:.center, spacing:40){Image("avarta1").modifier(myImageStyle())Image("avarta2").modifier(myImageStyle())Image("avarta3").modifier(myImageStyle())}.padding()}}structmyImageStyle:ViewModifier{func body(content:Content)->someView{ content.frame(width:200, height:200, alignment:.leading).cornerRadius(100).clipped().saturation(0.0)}}
实例代码已经被整理成互动课程(共196节课程),已集成在Xcode互动教程中,免费下载地址:![https://itunes.apple.com/cn/app/id1063100471]
About
SwiftUI practices guidebook, written for humans.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.

































































































