SwiftUI Essentials
SwiftUI要點(diǎn)
Creating and Combining Views
- 創(chuàng)建和組合視圖
This tutorial guides you through building Landmarks — an iOS app for discovering and sharing the places you love. You’ll start by building the view that shows a landmark’s details.
To lay out the views, Landmarks uses stacks to combine and layer the image and text view components. To add a map to the view, you’ll include a standard MapKit component. As you refine the view’s design, Xcode provides real-time feedback so you can see how those changes translate into code.
Download the project files to begin building this project, and follow the steps below.
本教程將指導(dǎo)您構(gòu)建標(biāo)記 - 一個(gè)用于發(fā)現(xiàn)和分享您喜愛的地方的iOS應(yīng)用程序牡属。 您將首先構(gòu)建顯示地標(biāo)詳細(xì)信息的視圖。
為了布局視圖,地標(biāo)使用堆棧來組合和分層圖像和文本視圖組件。 要向視圖添加地圖,您將包含標(biāo)準(zhǔn)MapKit組件哈打。 在細(xì)化視圖的設(shè)計(jì)時(shí),Xcode提供實(shí)時(shí)反饋,以便您可以看到這些更改如何轉(zhuǎn)換為代碼昔穴。
下載項(xiàng)目文件以開始構(gòu)建此項(xiàng)目,并按照以下步驟操作提前。
Section 1
第1節(jié)
Create a New Project and Explore the Canvas
- 創(chuàng)建一個(gè)新項(xiàng)目并探索畫布
Create a new Xcode project that uses SwiftUI. Explore the canvas, previews, and the SwiftUI template code.
- 創(chuàng)建一個(gè)使用SwiftUI的新Xcode項(xiàng)目吗货。 瀏覽畫布,預(yù)覽和SwiftUI模板代碼狈网。
To preview and interact with views from the canvas in Xcode, ensure your Mac is running macOS 10.15 beta.
- 要預(yù)覽Xcode中畫布中的視圖并與之交互宙搬,請(qǐng)確保您的Mac正在運(yùn)行macOS 10.15 beta。
Step 4
- 第4步
In the Project navigator, click to select ContentView.swift.
- 在項(xiàng)目導(dǎo)航器中拓哺,單擊以選中ContentView.swift勇垛。
By default, SwiftUI view files declare two structures. The first structure conforms to the View protocol and describes the view’s content and layout. The second structure declares a preview for that view.
- 默認(rèn)情況下,SwiftUI視圖文件聲明了兩個(gè)結(jié)構(gòu)體士鸥。 第一個(gè)結(jié)構(gòu)提符合View協(xié)議闲孤,描述了視圖的內(nèi)容和布局。 第二個(gè)結(jié)構(gòu)體聲明該視圖的預(yù)覽础淤。
Step 5
In the canvas, click Resume to display the preview.
- 在畫布中崭放,單擊“恢復(fù)”以顯示預(yù)覽哨苛。
Tip
If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
- 如果畫布不可見,請(qǐng)選擇“編輯器”>“編輯器”和“畫布”以顯示它币砂。
Step 6
Inside the body property, change “Hello World” to a greeting for yourself.
- 在body屬性中建峭,將“Hello World”更改為自己的問候語。
As you change the code in a view’s body property, the preview updates to reflect your changes.
- 當(dāng)您更改視圖的body屬性中的代碼時(shí)决摧,預(yù)覽會(huì)更新以反映您的更改亿蒸。
Section 2
- 第2節(jié)
Customize the Text View
- 自定義文本視圖
You can customize a view’s display by changing your code, or by using the inspector to discover what’s available and to help you write code.
- 您可以通過更改代碼或使用檢查器發(fā)現(xiàn)可用內(nèi)容并幫助您編寫代碼來自定義視圖的顯示。
As you build the Landmarks app, you can use any combination of editors: the source editor, the canvas, or the inspectors. Your code stays updated, regardless of which tool you use.
- 在構(gòu)建Landmarks應(yīng)用程序時(shí)掌桩,您可以使用任何編輯器組合:源編輯器边锁,畫布或檢查器。 無論您使用哪種工具波岛,代碼都會(huì)保持更新茅坛。
Next, you’ll customize the text view using the inspector.
- 接下來,您將使用檢查器自定義文本視圖则拷。
Step 1
In the preview, Command-click the greeting to bring up the structured editing popover, and choose Inspect.
- 在預(yù)覽中贡蓖,按住Command鍵并單擊問候語以顯示結(jié)構(gòu)化編輯彈出窗口,然后選擇“檢查”煌茬。
The popover shows different attributes that you can customize, depending on the type of view you inspect.
- 彈出窗口顯示您可以自定義的不同屬性斥铺,具體取決于您檢查的視圖類型。
Step 2
Use the inspector to change the text to “Turtle Rock”, the name of the first landmark you’ll show in your app.
-使用檢查器將文本更改為“Turtle Rock”坛善,即您將在應(yīng)用中顯示的第一個(gè)地標(biāo)的名稱晾蜘。
Step 3
Change the Font modifier to Title.
- 將“字體”修改器更改為“標(biāo)題”。
This applies the system font to the text so that it responds correctly to the user’s preferred font sizes and settings.
- 這將系統(tǒng)字體應(yīng)用于文本眠屎,以便它正確響應(yīng)用戶的首選字體大小和設(shè)置剔交。
Step 4
Edit the code by hand to add the .color(.green) modifier; this changes the text’s color to green.
- 手動(dòng)編輯代碼以添加.color(.green)修飾符; 這會(huì)將文本的顏色更改為綠色。
To customize a SwiftUI view, you call methods called modifiers. Modifiers wrap a view to change its display or other properties. Each modifier returns a new view, so it’s common to chain multiple modifiers, stacked vertically.
- 要自定義SwiftUI視圖改衩,請(qǐng)調(diào)用稱為修飾符的方法省容。 修改器包裝視圖以更改其顯示或其他屬性。 每個(gè)修改器都返回一個(gè)新視圖燎字,因此鏈接垂直堆疊的多個(gè)修改器是很常見的。
Your code is always the source of truth for the view. When you use the inspector to change or remove a modifier, Xcode updates your code immediately to match.
- 您的代碼始終是視圖的真實(shí)來源阿宅。 當(dāng)您使用檢查器更改或刪除修改器時(shí)候衍,Xcode會(huì)立即更新您的代碼以匹配。
Step 5
This time, open the inspector by Command-clicking on the Text declaration in the code editor, and then choose Inspect from the popover.
- 這次洒放,通過在代碼編輯器中單擊文本聲明來打開檢查器蛉鹿,然后從彈出框中選擇Inspect。
Click the Color pop-up menu and choose Inherited to change the text color to black again.
- 單擊“顏色”彈出菜單往湿,然后選擇“繼承”以再次將文本顏色更改為黑色妖异。
Step 6
Notice that Xcode updates your code automatically to reflect the change, removing the color(.green) modifier.
- 請(qǐng)注意惋戏,Xcode會(huì)自動(dòng)更新代碼以反映更改,刪除顏色(.green)修飾符他膳。
Section 3
- 第3節(jié)
Combine Views Using Stacks
- 使用堆棧組合視圖
Beyond the title view you created in the previous section, you’ll add text views to contain details about the landmark, such as the name of the park and state it’s in.
- 除了您在上一部分中創(chuàng)建的標(biāo)題視圖之外响逢,您還將添加文本視圖以包含有關(guān)地標(biāo)的詳細(xì)信息,例如公園的名稱和狀態(tài)棕孙。
When creating a SwiftUI view, you describe its content, layout, and behavior in the view’s body property; however, the body property only returns a single view. You can combine and embed multiple views in stacks, which group views together horizontally, vertically, or back-to-front.
- 在創(chuàng)建SwiftUI視圖時(shí)舔亭,您可以在視圖的body屬性中描述其內(nèi)容,布局和行為; 但是蟀俊,body屬性僅返回單個(gè)視圖钦铺。 您可以在堆棧中組合和嵌入多個(gè)視圖,這些視圖將視圖水平肢预,垂直或從后到前組合在一起矛洞。
In this section, you’ll use a vertical stack to place the title above a horizontal stack that contains details about the park.
- 在本節(jié)中,您將使用垂直堆棧將標(biāo)題置于包含公園詳細(xì)信息的水平堆棧上方烫映。
You can use Xcode’s structured editing support to embed a view in a container view, open an inspector, or help with other useful changes.
- 您可以使用Xcode的結(jié)構(gòu)化編輯支持將視圖嵌入容器視圖沼本,打開檢查器或幫助進(jìn)行其他有用的更改。
Step 1
Command-click the text view’s initializer to show the structured editing popover, and then choose Embed in VStack.
- 按住Command鍵并單擊文本視圖的初始值設(shè)定項(xiàng)以顯示結(jié)構(gòu)化編輯彈出窗口窑邦,然后選擇“嵌入VStack”擅威。
Next, you’ll add a text view to the stack by dragging a Text view from the library.
- 接下來,您將通過從庫(kù)中拖動(dòng)文本視圖將文本視圖添加到堆棧冈钦。
Step 2
Open the Library by clicking the plus button (+) at the top-right of the Xcode window, and then drag a Text view to the place in your code immediately after the “Turtle Rock” text view.
- 單擊Xcode窗口右上角的加號(hào)按鈕(+)打開庫(kù)郊丛,然后在“Turtle Rock”文本視圖后立即將Text視圖拖到代碼中的位置。
Step 3
Replace the Text view’s placeholder text with Joshua Tree National Park.
- 用Joshua Tree National Park替換文本視圖的占位符文本瞧筛。
Customize the location to match the desired layout.
- 自定義位置以匹配所需的布局厉熟。
Step 4
Set the location’s font to .subheadline.
- 將位置的字體設(shè)置為.subheadline。
Step 5
Edit the VStack initializer to align the views by their leading edges.
- 編輯VStack初始值設(shè)定項(xiàng)以按前導(dǎo)對(duì)齊視圖较幌。
By default, stacks center their contents along their axis and provide context-appropriate spacing.
- 默認(rèn)情況下揍瑟,堆棧將其內(nèi)容沿其軸居中,并提供適合上下文的間距乍炉。
Next, you’ll add another text view to the right of the location, this for the park’s state.
- 接下來绢片,您將在該位置的右側(cè)添加另一個(gè)文本視圖,這是該公園的狀態(tài)岛琼。
Step 6
In the canvas, Command-click on Joshua Tree National Park, and choose Embed in HStack.
- 在畫布上底循,按住Command鍵點(diǎn)擊Joshua Tree National Park,然后選擇嵌入HStack槐瑞。
Step 7
Add a new text view after the location, change the placeholder text to the park’s state, and then set its font to .subheadline.
- 在位置后添加新的文本視圖熙涤,將占位符文本更改為park的狀態(tài),然后將其字體設(shè)置為.subheadline。
Step 8
To direct the layout to use the full width of the device, separate the park and the state by adding a Spacer to the horizontal stack holding the two text views.
- 要指示布局使用設(shè)備的整個(gè)寬度祠挫,請(qǐng)通過將Spacer添加到包含兩個(gè)文本視圖的水平堆棧來分隔駐留和狀態(tài)那槽。
A spacer expands to make its containing view use all of the space of its parent view, instead of having its size defined only by its contents.
- spacer展開以使其包含視圖使用其父視圖的所有空間,而不是僅通過其內(nèi)容定義其大小等舔。
Step 9
Finally, use the padding() modifier method to give the landmark’s name and details a little breathing room.
- 最后骚灸,使用padding()修飾符方法為地標(biāo)的名稱和細(xì)節(jié)提供一點(diǎn)呼吸空間。
Section 4
Create a Custom Image View
- 創(chuàng)建自定義圖像視圖
With the name and location views all set, the next thing to do is to add an image for the landmark.
- 通過設(shè)置名稱和位置視圖软瞎,接下來要做的是為地標(biāo)添加圖像逢唤。
Instead of adding more code in this file, you’ll create a custom view that applies a mask, border, and drop shadow to the image.
- 您將創(chuàng)建一個(gè)自定義視圖,將遮罩涤浇,邊框和陰影應(yīng)用于圖像鳖藕,而不是在此文件中添加更多代碼。
Start by adding an image to the project’s asset catalog.
- 首先將圖像添加到項(xiàng)目的資產(chǎn)目錄中只锭。
Step 1
Find turtlerock.png in the project files’ Resources folder; drag it into the asset catalog’s editor. Xcode creates a new image set for the image.
- 在項(xiàng)目文件的Resources文件夾中找到turtle rock.png; 將其拖到資產(chǎn)目錄編輯器中著恩。 Xcode為圖像創(chuàng)建新的圖像集。
Next, you’ll create a new SwiftUI view for your custom image view.
- 接下來蜻展,您將為自定義圖像視圖創(chuàng)建一個(gè)新的Swift UI視圖喉誊。
Step 2
Choose File > New > File to open the template selector again. In the User Interface section, click to select SwiftUI View and click Next. Name the file CircleImage.swift and click Create.
- 選擇“文件”>“新建”>“文件”以再次打開模板選擇器 在“用戶界面”部分中,單擊以選中“SwiftUI視圖”纵顾,然后單擊“下一步”伍茄。 將文件命名為CircleImage.swift,然后單擊“創(chuàng)建”施逾。
You’re ready to insert the image and modify its display to match the desired design.
- 您已準(zhǔn)備好插入圖像并修改其顯示以匹配所需的設(shè)計(jì)敷矫。
Step 3
Replace the text view with the image of Turtle Rock by using the Image(_:) initializer.
- 使用Image(_ :)初始值設(shè)定項(xiàng)將文本視圖替換為Turtle Rock的圖像。
Step 4
Add a call to .clipShape(Circle()) to apply the circular clipping shape to the image.
- 添加對(duì).clipShape(Circle())的調(diào)用以將圓形剪裁形狀應(yīng)用于圖像汉额。
The Circle type is a shape that you can use as a mask, or as a view by giving the circle a stroke or fill.
- 圓形類型是一種可用作蒙版的形狀曹仗,或通過為圓形提供筆觸或填充的視圖。
Step 5
Create another circle with a gray stroke, and then add it as an overlay to give the image a border.
- 創(chuàng)建另一個(gè)帶有灰色筆觸的圓蠕搜,然后將其添加為疊加層以為圖像添加邊框怎茫。
Step 6
- Next, add a shadow with a 10 point radius.
接下來,添加半徑為10點(diǎn)的陰影妓灌。
Step 7
Switch the border color to white.
- 將邊框顏色切換為白色轨蛤。
This completes the image view.
- 這樣就完成了圖像視圖。
Section 5
Use UIKit and SwiftUI Views Together
- 一起使用UIKit和SwiftUI視圖
Now you’re ready to create a map view. You can use the MKMapView class from MapKit to render the map.
- 現(xiàn)在您已準(zhǔn)備好創(chuàng)建地圖視圖虫埂。 您可以使用MapKit中的MKMapView類來渲染地圖俱萍。
To use UIView subclasses from within SwiftUI, you wrap the other view in a SwiftUI view that conforms to the UIViewRepresentable protocol. SwiftUI includes similar protocols for WatchKit and AppKit views.
- 要在SwiftUI中使用UIView子類,可以將其他視圖包裝在符合UIViewRepresentable協(xié)議的SwiftUI視圖中告丢。 SwiftUI包含WatchKit和AppKit視圖的類似協(xié)議。
To get started, you’ll create a new custom view that can present an MKMapView.
- 首先,您將創(chuàng)建一個(gè)可以呈現(xiàn)MKMapView的新自定義視圖岖免。
Step 1
Choose File > New > File, select iOS as the platform, select the SwiftUI View template, and click Next. Name the new file MapView.swift and click Create.
- 選擇File> New> File岳颇,選擇iOS作為平臺(tái),選擇SwiftUI View模板颅湘,然后單擊Next话侧。 將新文件命名為MapView.swift,然后單擊“創(chuàng)建”闯参。
Step 2
Add an import statement for MapKit, and declare UIViewRepresentable conformance for the MapView type.
- 為MapKit添加import語句瞻鹏,并為MapView類型聲明UIViewRepresentable一致性。
Don’t worry about the error that Xcode displays; you’ll fix that in the next few steps.
- 不要擔(dān)心Xcode顯示的錯(cuò)誤; 你將在接下來的幾個(gè)步驟中解決這個(gè)問題鹿寨。
The UIViewRepresentable protocol has two requirements you need to add: a makeUIView(context:) method that creates an MKMapView, and an updateUIView(_:context:) method that configures the view and responds to any changes.
- UIViewRepresentable協(xié)議有兩個(gè)需要添加的要求:創(chuàng)建MKMapView的makeUIView(context :)方法和配置視圖并響應(yīng)任何更改的updateUIView(_:context :)方法新博。
Step 3
Replace the body property with a makeUIView(context:) method that creates and returns an empty MKMapView.
- 用makeUIView(context :)方法替換body屬性,該方法創(chuàng)建并返回一個(gè)空的MKMapView脚草。