-
Introducing Swift UI 예제 정리SwiftUI/Document 예제 2020. 12. 16. 10:00
SwiftUI is a modern way to declare user interfaces for any Apple platform. Create beautiful, dynamic apps faster than ever before.
해석 : 스유는 애플 플랫폼을 위해 UI를 선언하는 현대적인 방법이다. 아름답고, 전래없이 빠른 동적 앱들을 창조해보세요.
생각 : 흠.. 역시 애플. 아름다움을 강조하는 구만. 근데 스유의 어떤게 아름다운진 모르겠다만 ㅋㅋ
*애플 예제를 보면서 참고해주세요 :)*
- 예제 링크 : developer.apple.com/tutorials/swiftui/creating-and-combining-views
Creating and Combining Views
This tutorial guides you through building Landmarks — an 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.
랜드마크를 만드는 앱! 뭔가 벌써 재미가 없는 느낌.. ㅋㅋ 그래도 이 튜토리얼로 stack을 사용해보고 image와 text view 컴포넌트들을 사용해 뷰를 구성해볼 수 있다네요. view에 map도 추가해보고, Mapkit 컴포넌트들도 사용해보네요. 함 들어가보죠!!!
준비 사항
다운받으라는 파일을 다운 받고 XCode 12 이상으로 업데이트 및 macOS BigSur로 업뎃!
Section1
Create a New Project and Explore the Canvas
SwiftUI를 사용한 프로젝트를 생성 후 canvas, preview, template code 들을 둘러보자
- XCode에서는 canvas에서 view들과 상호작용 및 미리보기가 가능하다.
Step 1
Open Xcode and either click “Create a new Xcode project” in Xcode’s startup window, or choose File > New > Project.
해석 : XCode를 열고 "Create a new XCode project"를 클릭하거나 File > New > Project를 통해 새로운 프로젝트 생성
Step 2
In the template selector, select iOS as the platform, select the App template, and then click Next.
해석 : template 선택하는 곳에서 iOS 플랫폼에서 App을 선택하고 클릭
Step 3
Enter “Landmarks” as the product name, select “SwiftUI” for the interface and “SwiftUI App” for the life cycle, and click Next. Choose a location to save the Landmarks project on your Mac.
해석 : product name에 "Landmarks"를 입력하고 "SwiftUI"를 선택하고 life cycle은 "SwiftUI App"을 선택하라. next를 누르고 당신의 사용자의 Mac에 Landmarks 프로젝트를 저장하라.
*참고 : Interface를 Storyboard로 하게되면 SwiftUI가 아닌 Swift를 사용하기에 더 적합한 환경이 보여질 것이다. SwiftUI를 처음 접하는 분들에게는 여기서 혼동이 올텐데 뭔가 이상하다 싶으면 제일 먼저 이곳을 제대로 체크했는지 확인해보자. Life Cycle 부분의 차이에 있어서는 나중에 기회가 되면 정리해서 링크 걸어놓을게요 :). -> 뭔가 차이점을 알 것 같은데 SwiftUI의 Life Cycle을 모르니 차이점을 비교를 못하겠음.. 나중에 꼭 정리해볼게요 ㅠㅜ
좌측이 SwiftUI, SwiftUI App을 선택한 프로젝트, 우측이 Storyboard와 UIKit Delegate를 선택 후 생성한 프로젝트 기본 생성 파일들 Step 4
In the Project navigator, select LandmarksApp.swift.
An app that uses the SwiftUI app life cycle has a structure that conforms to the App protocol. The structure’s body property returns one or more scenes, which in turn provide content for display. The @main attribute identifies the app’s entry point.
해석 : Project navigator 내부에서 "LandmarksApp.swift" 파일을 클릭해보자. (좌측 파일들이 모여 있는 곳을 project navigator라고 칭한다. navigator pane 이라고도 함). 이 Landmarks 앱은 App 프로토콜을 준수하는 LandmarksApp 구조체를 가지고 있는 SwiftUI app life cycle를 사용한다. LandmarksApp 구조체의 body property는 보여질 컨텐츠를 차례대로 제공하는 한가지 이상의 scene들을 반환한다. @main 속성(=attribute)은 앱의 entry point(=진입점)임을 나타낸다.
*정리 : 흠.. SwiftUI App Life Cycle은 App 프로토콜의 구조에 따라 작동되는 것 같다. 그리고 App 프로토콜을 준수하는 구조체에서 전체 Scene 들을 관리하는 것 같다. 또한 @main attribute가 앱이 시작될때 가장 먼저 실행됨을 알려주는 것 같다.
Step 5
In the Project navigator, select 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.
해석 : 다음은 "ContentView.swift" 파일을 보자. 기본적으로 SwiftUI view 파일들은 두 가지 구조체들을 선언한다. 하나는 View 프로토콜을 준수하고 뷰들의 컨텐츠와 레이아웃들을 묘사하는 구조체이고, 또 다른 하나는 view를 미리볼 수 있도록 선언하는 구조체이다.
*정리 : 기존 UIKit을 사용한 프로젝트에서는 시뮬레이터를 돌려야지만 어떻게 작동하는 지를 확인할 수 있었는데, SwiftUI는 preview를 통해서 바로바로 어떻게 동작하는지를 알 수 있다는 것이 장점 중 하나인 것 같다. 이를 가능케 해주는 것이 기본적으로 선언되어 있는 "view를 미리볼 수 있도록 선언하는 구조체"인 "ContentView_Previews" 인 것 같다. 또한 View 프로토콜을 준수하는 또 다른 구조체 "ContentView"는 컨텐츠와 레이아웃을 구성할 수 있는 구조체 인 것 같다.
Step 6
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Canvas to show it.
해석 : canvas에서 preview를 보이게 하려면 "Resume" 버튼을 클릭하면 된다. canvas가 보이지 않는다면 Editor > Canvas를 클릭하면 된다.
*정리 : canvas가 preview를 볼 수 있게 하는 창을 의미한다.
Step 7
Inside the body property, change “Hello, World!” to a greeting for yourself.
As you change the code in a view’s body property, the preview updates to reflect your changes.
해석 : "ContentView" 구조체 내부에 있는 body property 내부에 Hello World를 바꿔봐라. view 내부의 body property의 코드를 변경하면 preview는 변경된 것을 반영하여 업데이트 한다.
*정리 : view 내부 body property를 변경하면 바로 반영됨!!! 싱기
Section 2
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.
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.
*정리 : 뷰를 커스터마이징 할때 코드를 사용할 수도, 아니면 inspector를 통해 수정할 수도 있다. 그리고 앱 만들때, source editor, canvas, inspector를 이용할 수 있다. 어떤 걸 사용해서 코드를 업데이트 하든 상관없다.
Next, you’ll customize the text view using the inspector.
해석 : 우리는 text view를 inspector를 사용해서 커스터마이징 해보자.
드디어 UI 구성 시작!!!
Step 1
In the preview, Command-click the greeting to bring up the structured editing popover, and choose “Show SwiftUI Inspector”.
The popover shows different attributes that you can customize, depending on the type of view you inspect.
해석 : preview에서 Command을 누르고 마우스로 클릭을 하면 구성된 수정 가능한 popover가 뜰 것이다. 여기서 "Show SwiftUI Inspector"를 선택하라. popover는 너가 검사하는 뷰의 타입에 따라 커스터마이징 할 수 있는 다른 속성들을 보여준다.
Step 2
Use the inspector to change the text to “Turtle Rock”, the name of the first landmark you’ll show in your app.
해석 : inspector를 사용하여 text를 "Turtle Rock"으로 변경하라. 이것은 너의 앱에 보여질 첫 번째 랜드마크 이름이다.
Step 3
Change the Font modifier to “Title”.
This applies the system font to the text so that it responds correctly to the user’s preferred font sizes and settings.
해석 : Font modifier를 "Title"로 변경하여라. 이는 텍스트에 시스템 폰트를 적용시켜서 유저가 선호하는 폰트 사이즈와 세팅에 정확하게 반응한다.
중요 : 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 뷰를 커스텀하기 위해서는 "modifiers"라고 불리는 method를 호출해야 한다. Modifier들은 뷰의 보여짐과 다른 속성들을 변경하기 위해 뷰를 감싼다 각각의 modifier는 새로운 뷰를 리턴하기에 다수의 modifier들을 수직적으로 stack을 쌓는 것은 흔하다.
*참고 : modifier는 각 뷰들의 property들을 수정하기 위해 쓰인다. 만약 다수의 property들을 수정하고 싶을때는 수직으로 계속 나열해서 작성하면 된다.
*사용법 : 변경하고자 하는 View의 아래에 .을 붙히고 변경하고자 하는 property를 변경하면 된다.Step 4
Edit the code by hand to change the padding() modifier to the foregroundColor(.green) modifier; this changes the text’s color to green.
해석 : .padding() modifier를 .foregroundColor(.green)으로 변경해보자. 이건 text 색깔을 green으로 바꿔준다.
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.
-> 코드는 항상 뷰에 적용된다. inspector을 사용하여 modifier를 변경하거나 지울때, XCode는 당신의 코드를 변경에 맞추어 즉시 업데이트 한다.Step 5
This time, open the inspector by Command-clicking on the Text declaration in the code editor, and then choose “Show SwiftUI Inspector” from the popover. Click the Color pop-up menu and choose Inherited to change the text color to black again.
해석 : 이번엔 code editor의 Text 선언에 Command 클릭을 해서 inspector를 열고 "Show SwiftUI Inspector"를 선택한다. Color 메뉴를 선택하고 Inherited를 Black으로 다시 변경한다.
Step 6
Notice that Xcode updates your code automatically to reflect the change, removing the foregroundColor(.green) modifier.
해석 : XCode가 자동적으로 변경을 반영했다는 것을 알 수 있다. 그리고 .foregroundColor(.green) modifier가 사라졌다.
*참고 : 음? 나는 .foregroundColor(.green) modifier는 사라지지 않고 .black으로 변경됨.... ㅜㅡㅜ
Section 3
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.
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.
In this section, you’ll use a vertical stack to place the title above a horizontal stack that contains details about the park.
해석 : 이전 section에선 title뷰를 생성한 것 외에도 landmark에 대한 디테일을 포함하는 textView를 추가하라. SwiftUI 뷰를 생성할때, 뷰의 컨텐츠, 레이아웃, 행동들을 body property 내부에 구현하라. 그러나 body property는 오로지 단일 뷰만 반환한다. 우린 수직, 수평, 앞 뒤로 묶도록 하는 stack을 통해 다수의 뷰들을 결합하고 embed 시킬 수 있다. 이번 섹션에선 vertical stack(VStack - 수직으로 정렬)을 사용하여 공원에 대한 디테일을 포함하는 horizontal stack(HStack - 수평으로 정렬) 위에 title을 위치시킬 것이다.
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에서 지원하는 inspector에서 view embed를 지원하는 메뉴를 사용할 수 있다.
* SwiftUI에서 Stack은 UIKit의 StackView와 같다.Step 1
Command-click the text view’s initializer to show the structured editing popover, and then choose “Embed in VStack”.
해석 : text view의 생성자(=intializer)에 대고 command 클릭을 하면 popover 메뉴가 뜨는데, "Embed in VStack"을 선택하라
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 below the “Turtle Rock” text view.
해석 : XCode의 우측 상단에 있는 (+) 버튼을 눌러 라이브러리를 열고 Text view를 끌고와 "Turtle Rock" text view 하단에 위치시켜라.
*팁 : Shift + command + enter를 누르면 Library가 바로 열린다. (유용할테니 알아두면 좋음!)
Step 3
Replace the Text view’s placeholder text with “Joshua Tree National Park”.
해석 : Joshua Tree National Park”로 text를 변경해라
Step 4
Set the location’s font to subheadline.
해석 : location의 text view의 폰트를 .subheadline으로 바꿔라.
Step 5
Edit the VStack initializer to align the views by their leading edges.
By default, stacks center their contents along their axis and provide context-appropriate spacing.
해석 : VStack initializer를 수정하여 alignment를 .leading으로 변경하라. stack들은 기본적으로 axis(=축)을 따라 컨텐츠를 중앙에 배치하고 상황에 맞는 spacing(=간격)을 제공한다. (처음 하시는 분들은 아직 어색하겠지만 이런 단어에 익숙해지셔야 해요 ㅠㅡㅠ)
*다음은 공원의 주(=state)를 나타내는 text view를 추가하자
Step 6
In the canvas, Command-click “Joshua Tree National Park”, and choose “Embed in HStack”.
해석 : canvas에서 “Joshua Tree National Park”에 마우스를 두고 command 클릭을 한 후 "Embed in HStack"을 클릭하자
-> HStack을 통해 공원 이름 text와 state를 나타내는 text view를 수평으로 나열한 stack으로 묶을 수 있다.
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.
해석 : 위치 text view 옆에 text view를 추가하고 공원의 주를 적어 넣고 font를 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.
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.
해석 : layout이 device의 모든 넓이를 사용하도록 하려면, 두 개의 text view를 감싸는 HStack에 Spacer를 추가하여 공원과 주를 분리시켜야 한다.
Spacer는 컨텐츠가 정의된 특정 사이즈를 가지는 것 대신 spacer를 포함하는 뷰가 부모 뷰의 모든 공간을 사용하도록 확장시킨다.
-> 보충 설명 : 현재 park와 state를 나타내는 text들을 포함하는 HStack이 있잖아요? Spacer를 Hstack 내부의 Text들 사이에 위치시킴으로서 HStack이 device의 모든 넓이를 사용하도록 해줍니다. 그래서 preview를 보면 park text view와 state text view가 양 끝에 위치하게 되는 겁니다. 왜냐? spacer가 자신의 parent view인 HStack이 device의 모든 넓이를 사용할 수 있도록 했기 때문이죠.
예시로, Spacer()를 state를 나타내는 Text view 아래에다가 놓으면 아래 이미지와 같이 오른쪽이 비게 되죠.
Step 9
Finally, use the padding() modifier method to give the landmark’s name and details a little more space.
해석 : 마지막으로 .padding() modifier method를 landmark name과 details에 주면 조그만 공간이 생깁니다.
Swift랑 완전 똑같음! 역시 UIKit 기반 프레임워크라 그런지 배우기는 수월!
Section4
Create a Custom Image View
With the name and location views all set, the next step is to add an image for the landmark.
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.
해석 : 모두 세팅된 이름, 위치 뷰들과 함께, landmark를 나타내는 image를 추가해보자. file에 코드를 더 작성하기 보단, mask, border, shadow를 image에 적용시킨 custom view를 만들어보자.
Step 1
Find turtlerock@2x.jpg in the project files’ Resources folder; drag it into the asset catalog’s editor. Xcode creates a new image set for the image.
해석 : 위에서 다운받은 프로젝트 파일에서 "turtlerock@2x.jpg"를 찾아서 asset catalog 에디터에 드래그해라. XCode는 이미지의 새로운 이미지를 만든다.
Step 2
Choose File > New > File to open the template selector again. In the User Interface section, select “SwiftUI View” and click Next. Name the file CircleImage.swift and click Create.
해석 : File > New > File에서 template selector를 열고, "SwiftUI View"를 클릭후 "CircleImage.swift" 파일을 생성한다. (파일 생성시 이름은 CircleImage만 치면 된다)
Step 3
Replace the text view with the image of Turtle Rock by using the Image(_:) initializer, passing it the name of the image to display.
해석 : text view 대신 Image(_:) initializer를 사용하여 Turtle Rock 이미지로 대체하고, 보여줄 이미지의 이름을 넣어라
Step 4
Add a call to clipShape(Circle()) to apply the circular clipping shape to the image.
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.
해석 : 원형으로 잘라낸 이미지의 모양을 적용하기 위해 clipShape(Circle())을 호출하라. Circle 타입은 원을 획 또는 채움으로서 mask나 뷰처럼 사용할 수 있는 모양이다.
*보충설명 : clipShape과 Circle 이란?
-> UIKit을 공부해본 사람이라면 원형 image view를 만들때 .borderRadius property를 width or height 1/2로 줘본적이 있을 것이다. 뭔가 내 생각에는 이걸 그냥 Circle이라는 구조체로 만들어놓은게 아닌가 싶다.
func clipShape<S>(_ shape: S, style: FillStyle = FillStyle()) -> some View where S : Shape
option + click을 해서 위 clipShape라는 함수의 parameter를 보면 shape는 뷰에 사용될 clipping shape이고, 뷰의 aspect ratio(=화면 비율)에 맞추어 뷰의 프레임을 채워줄 모양이다. -> 쉽게 풀자면 shape 파라미터로 던져준 애로 모양을 만들어준다 이 말이다. Circle 말고도 Rectangle도 있다. (아직 내가 아는건 이 두개다 ㅋㅋ)
style 파라미터는 모양을 rasterize 할때 사용된다고 하는데 rasterize가 뭔지 잘 모르겠다..ㅜ (*rasterize : 래스터화하다(텍스트와 이미지를 프린터 가능한 형태로 전환시키다 -> 언제 쓰이는지 아직 잘 모르겠음)
Step 5
Create another circle with a gray stroke, and then add it as an overlay to give the image a border.
해석 : 회색으로 된 또다른 circle을 하나 생성하고 image의 border로 overlay 해줘라. (stroke : 획, overlay : 덧씌우다)
*보충설명
.overlay 메소드는 아래 이미지에 선언되어 있는 것과 같이 View를 파라미터로 받아서 View를 리턴한다. 즉 overlay 시킬 뷰를 파라미터로 넣으면 그 뷰를 본래의 View에 overlay 시킨다.
stroke 메소드는 아래 코드처럼 구현되어 있다.
func stroke<S>(_ content: S, lineWidth: CGFloat = 1) -> some View where S : ShapeStyle
stroke의 파라미터 중 content는 색깔이나 경사와 같이 모양을 변경할 수 있는 것이고, lineWidth는 라인의 두께를 결정한다.
Image("turtlerock") .clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/) .overlay(Circle().stroke(Color.gray, lineWidth: 4))
자 그럼 위 이미지에서 사용된 overlay의 경우에는 Circle 뷰를 하나 생성을 한 후에 색깔을 회색으로 바꾼 후 두께를 4로 주어서 덮어 씌웠다.
Step 6
Next, add a shadow with a 7 point radius.
해석 : 다음은 7 포인트 size의 shadow를 먹였다.
*보충설명
func shadow(color: Color = Color(.sRGBLinear, white: 0, opacity: 0.33), radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0) -> some View
shadow 메소드는 위 처럼 선언되어 있고, 아래 이미지와 같은 파라미터들을 가진다..
color의 경우 그림자의 색깔을 설정하고, radius 같은 경우 그림자의 사이즈를 결정한다 (번지는 정도?랄까). x는 뷰에 적용될 shadow의 가로의 위치를 적용 시키고 y는 세로의 위치를 적용시킨다.
Step 7
Switch the border color to white.
This completes the image view.
해석 : border color를 흰색으로 바꿔라
그럼 끝~
Section 5
Use SwiftUI Views From Other Frameworks
Next you’ll create a map that centers on a given coordinate. You can use the Map view from MapKit to render the map.
해석 : 다음은 주어진 좌표가 중앙에 뜨는 맵을 생성해볼 것이다.
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 플랫폼에서 "SwiftUI View" 템플릿을 선택 후 MapView라는 이름의 swift 파일 생성
Step 2
Add an import statement for MapKit.
When you import SwiftUI and certain other frameworks in the same file, you gain access to SwiftUI-specific functionality provided by that framework.
해석 : MapKit을 import 시켜라 -> 이것은 MapKit 프레임워크에 들어있는 컴포넌트들을 사용한다는 의미이다.
같은 파일에 SwiftUI나 다른 프레임워크들을 import 시킨다면, 당신은 그 프레임워크로 부터 SwiftUI의 구체적인 함수들에 접근이 가능하다.
Step 3
Create a private state variable that holds the region information for the map.
You use the @State attribute to establish a source of truth for data in your app that you can modify from more than one view. SwiftUI manages the underlying storage and automatically updates views that depend on the value.
해석 : 맵을 위한 지역 정보를 가지고 있는 private한 state 변수를 만들어라
당신은 @State 속성을 사용하여 앱에서 하나 이상의 view에서 수정할 수 있는 데이터의 source of truth를 구축할 수 있다.
SwiftUI는 드러나지 않은(=underlying) 저장소를 관리하고 자동적으로 value에 따라 view들을 업데이트 한다.
*정리 : 쉽게 생각하면 @State는 선언된 변수의 값의 변경에 따라 다른 뷰들의 데이터들을 수정가능하게 해주는 속성임.
Step 4
Replace the default Text view with a Map view that takes a binding to the region.
By prefixing a state variable with $, you pass a binding, which is like a reference to the underlying value. When the user interacts with the map, the map updates the region value to match the part of the map that’s currently visible in the user interface.
해석 : 기본 Text를 region에 binding 되는 Map view로 대체하라 -> region 값에 따라 Map view가 보여주는 곳이 다름. 그냥 region을parameter로 가지는 Map View를 만들어라 라는 말인 것 같음.
state 변수 앞에 $를 접두사로 붙히면, 드러나지 않은(=underlying) 값에 참조하여 연관 값을 패스할 수 있다. 유저가 map과 상호작용 할 때, 맵은 현재 UI에서 보여주는 맵의 일부분을 매치시켜 region 값을 업데이트 한다. -> 유저가 UI를 스크롤하여 Map을 움직일때마다 region 값이 변경되는데 그 값이 @State에 저장이 되고 $을 붙인 $region은 그 값이 업데이트 된다라는 말 임.
*참고 : 여기서 undelying value 는 앱 내부에서 각 뷰들끼리 상호작용 가능한 값을 의미하는 것 같음.
When previews are in static mode, they only fully render native SwiftUI views. For the Mapview, you’ll need to switch to a live preview to see it render.
해석 : preview가 static(=동적) 모드 일땐, preview는 오직 native SwiftUI 뷰들만을 보여준다. MapView를 동작하기 위해선 렌더링을 볼 수 이는 live preview로 변경해줘야 한다.Step 5
Click Live Preview to switch the preview to live mode. You might need to click Try Again or Resume above your preview.
In a moment, you’ll see a map centered on Turtle Rock. You can manipulate the map in live preview to zoom out a bit and see the surrounding area.
해석: live mode를 클릭하여 preview를 Live preview로 변경해줘라. 다시 클릭하거나 프리뷰 위의 Resume 버튼을 누르면 된다. 이때 우린 map 가운데의 Turtle Rock을 볼 수 있을 것이다. 우린 live preview를 축소할 수도 있고 근처 지역을 볼 수도 있다.
Section 6
Compose the Detail View
You now have all of the components you need — the name and place, a circular image, and a map for the location.
With the tools you’ve used so far, combine your custom views to create the final design for the landmark detail view.
해석 : 우린 필요한 모든 컴포넌트들을 가졌다. 이름, 장소, 동그란 이미지, 위치를 보여주는 map. 지금까지 사용한 도구들을 총합하여 landmark detail view를 위한 최종 디자인을 만들 수 있다.
Step 1
In the Project navigator, select the ContentView.swift file.
해석 : navigator에서 ContentView.swift 파일을 선택하라
Step 2
Embed the VStack that holds the three text views in another VStack.
해석 : 현재 있는 VStack을 또 다른 VStack으로 둘러싸라
Step 3
Add your custom MapView to the top of the stack. Set the size of the MapView with frame(width:height:).
When you specify only the height parameter, the view automatically sizes to the width of its content. In this case, MapView expands to fill the available space.
해석 : MapView를 VStack 내부의 최상위에 올려라. 그리고 MapView를 frame(width:height:)로 frame을 정해주어라. 당신이 오직 height parameter만을 정한다면, 뷰는 컨텐츠에 맞게 자동적으로 width의 사이즈를 측정한다. 이 경우 MapView는 가능한 공간을 모두 꽉채우도록 확장될 것이다.
Step 4
Click Live Preview to see the rendered map in the composed view.
You can continue editing the view while showing a Live Preview.
해석 : 구성된 뷰들에서 렌더링된 map을 보려면 Live Preview를 클릭해라. 우린 Live Preview가 보여지는 동안 view를 계속해서 편집할 수 있다. -> 여기서 편집은 Command - click을 누르는 편집이 아니다. 그냥 상호작용이 가능하다는 뜻이다.
Step 5
Add the CircleImage view to the stack.
해석 : Circleimage view도 Vstack에 추가하라.
Step 6
To layer the image view on top of the map view, give the image an offset of -130 points vertically, and padding of -130 points from the bottom of the view.
These adjustments make room for the text by moving the image upwards.
해석 : map view 위에 image view를 올리고 싶다면, image에 수직으로 -130 포인트 만큼 offset을 주고, view의 바텀으로 부터 -130 포인트 만큼 패딩을 줘야 한다.
이러한 조정들은 image를 위쪽으로 움직으로서 텍스트를 위한 공간을 만들어준다
*참고
CircleImage() .offset(y: -130) .padding(.bottom, -130)
padding과 offset의 차이가 궁금하다면 : garlic-onion.tistory.com/5
Step 7
Add a spacer at the bottom of the outer VStack to push the content to the top of the screen.
해석 : 스크린의 상단으로 컨텐츠를 놓고 싶다면, VStack 바깥의 하단에 spacer를 추가하라
*참고 : 만약 뭔가 이상하다 싶으면 시뮬레이터를 좀 더 긴 iPhone 11 pro max로 해보면 예제처럼 될 것이다.
Step 8
To allow the map content to extend to the top edge of the screen, add the ignoresSafeArea(edges: .top) modifier to the map view.
해석 : map 컨텐츠를 스크린의 상단까지 확장시키도록 하려면, ignoreSafeArea(edges: .top) modifier를 map view에 추가하라
Step 9
Add a divider and some additional descriptive text for the landmark.
해석 : divider와 landmark를 묘사할 추가적인 text를 추가하라
* 참고 : Divider는 Summary에 나와있는 것처럼 "A visual element that can be used to separate other content."이다. 각 컨텐츠를 분리시키는 시각적 element이다.
Step 10
Finally, move the subheadline font modifier from each Text view to the HStack containing them, and apply the secondary color to the subheadline text.
When you apply a modifier to a layout view like a stack, SwiftUI applies the modifier to all the elements contained in the group.
해석 : 최종적으로 subheadline font modifier를 각각의 Text view에서 그 Text view들을 포함하는 HStack 으로 옮기고, subheadline text에 secondary color를 적용시켜라. stack과 같은 layout view에 modifier를 적용시킬때 SwiftUI는 group 내부에 포함된 모든 element들에 modifier를 적용한다.
끝!!!!!!!!111
SwiftUI 예제를 처음 따라가며 느낀 점
- UIKit에서 했던 것과는 달라 좀 당황스러웠다. 특히 modifier가 적응이 쉽게 안되었고, @State 속성 같은 경우도 UIKit에서는 그냥 전역변수나 Class 내부의 변수를 선언해놓고 그냥 사용할 수 있었는데 @State가 붙어야만 값의 변경에 따라 view가 업데이트 된다는 것이 신기했다,
- UIKit의 method와 SwiftUI의 modifier의 개념에 있어서 엄청난 혼란이 왔다. UIKit에서는 구조체 내부에 함수를 선언하면 그것을. method라고 부르는데, 나는 말을 할때 그 구조체 인스턴스의 어떤 메소드를 사용해!라고 했다. 근데 SwiftUI에서는 갑자기 modifier라는 개념이 등장하는데 굳이 인스턴스 뒤에 .을 붙혀서 사용하는게 아니라 한 칸씩 뛰어서 사용해도 된다. 그래서 나는 modifier가 아예 다른 개념인 줄 알았는데 뭔가 하다보니 Method랑 하는 역할은 같지만, 가독성을 위해 한칸씩 들여쓰기 해도 잘 돌아가니 명칭을 modifier로 하자!라고 한 것 같다. 틀렸다면 꼭!꼭!꼭! 말해주면 감사하겠습니다 ㅜ
- view를 하나하나 커스텀 하다보니 신기했다. 일단 TableView와 같이 생성 후 delegate나 datasource에 알맞는 값만 넣어주어 만들기 쉬웠던 반면, SwiftUI는 하나하나 다 해주어야 해서 아직 어색하다.
- AutoLayout!!! 여기는 Space와 Padding을 가지고 layout을 잡는 것 같은데... 스토리보드에서의 AutoLayout에 익숙한 나로서는 아직 적응이 안되서 어색하다 ㅠㅜ 얼른 익숙해지면 좋겠다 ㅎㅎ
처음 글을 쓰다보니 중구난방으로 쓴 감이 있지만 도움이 되셨으면 좋겠습니다 ㅎㅎ
참고 : developer.apple.com/tutorials/swiftui/creating-and-combining-views
'SwiftUI > Document 예제' 카테고리의 다른 글
Handling User Input 예제 정리 (0) 2020.12.19 Building Lists and Navigation 예제 정리 (0) 2020.12.18 - UIKit에서 했던 것과는 달라 좀 당황스러웠다. 특히 modifier가 적응이 쉽게 안되었고, @State 속성 같은 경우도 UIKit에서는 그냥 전역변수나 Class 내부의 변수를 선언해놓고 그냥 사용할 수 있었는데 @State가 붙어야만 값의 변경에 따라 view가 업데이트 된다는 것이 신기했다,