[Translation] SwiftUI official tutorial (b)

Please complete Chinese tutorial and see github.com/WillieWangW...

Creating and combinations View

This section will guide you to build a place to discover and share your favorite App in iOS - Landmarks. First, we show the landmark building view details.

LandmarksUse stackswill image, textlike components are combined and layered, in order to give the layout view. If you want to add to the map view, we need to introduce standard MapKitcomponents. When we adjust the design, Xcode can make real-time feedback, so that we can see how these adjustments are converted to code.

Download the project file and follow the steps below.

  • Estimated Completion Time: 40 minutes
  • The initial project files: Download

1. Create a new project and view Canvas

Used SwiftUIto create a new Xcode project template app, and look at the canvas.

1.1 Open Xcode, click on Xcode startup window Create a new Xcode project, or select File> New> Project.

1.2 Select the iOSplatform, Single View Apptemplate, and then click Next.

1.3 input Landmarksas Product Name, check Use SwiftUIbox, and then click Next. Select a location to save the project.

1.4 Project navigator, check ContentView.swift.

By default, SwiftUIView document declares two structures. The first structure follow a Viewprotocol describing the content and layout view. The second view of the structure declaration preview.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

1.5 canvas, click Resumeto display a preview.

Tip: If you do not canvas, select Editor> Editor and Canvasto display.

1.6 bodyProperties, Hello Worldchange their greetings. When you change the code, the preview will be updated in real time.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello SwiftUI!")
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

2. Custom Text View

In order to customize the view of the display, we can change your code, or use inspectorto help us write code.

In the build Landmarksprocess, we can use any editor to work: write the source code, modify canvas, or through inspectors, no matter what tools to use, the code will be kept up to date.

Next, we use inspectorto customize text view.

2.1 In the preview, hold down Commandand click the greeting to display the editing window, and then select Inspect.

Editing window displays the different attributes can be modified, depending on which type of view.

2.2 with inspectorthe text changed Turtle Rock, this is the first landmark name displayed in the app.

2.3 will be Fontamended to Title.

This change makes the text using the system font, after which it will be able to display the user's preferences and font size settings are correct.

Edit the code by hand to add the .color(.green) modifier; this changes the text’s color to green.

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.

2.4 in the code to add .color(.green), change text color is green.

If you want to customize the SwiftUIview, we can call a class called modifiersmethods. Such methods to change the display attributes or other packaging a view. Each modifiersmethod returns a new view, a chain so we can call multiple modifiersmethods.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Turtle Rock")
            .font(.title)
            .color(.green)
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

view the true source of the code is in fact, when we used inspectorto modify or delete modifiersthe time, Xcode will update our code immediately.

2.5 This time we hold down in the code editor area Command, click Textthe statement to open inspector, and then select Inspect. Click the Color menu and select Inherited, so the text has changed back to black.

Note 2.6, Xcode will automatically update the code for modifications, such as deleting .color(.green).

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Turtle Rock")
            .font(.title)

    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

3. View combination with Stacks

After create a title on a view, let's add text view, which is used to display the subject of detailed information, such as the name and the state where the park.

Creating SwiftUItime view, we can view a bodydescription of its contents, layout and behavioral attributes. Since the bodyproperty returns only a single View, we can use Stacksto combine a plurality of View and embedding, so that they are horizontal, vertical or in order from back to front together.

In this section, we use levels stackto display the details of the park, and then perpendicular stackto the above details on the title.

We can use Xcode editing features will be embedded view to a container, you can use inspectoror helpfind more help.

3.1 Hold down Commandand click the text initialization method of view, select the edit window Embed in VStack.

Next, from the Librarydrag of a Text viewadded to the stackmedium.

3.2 Click the plus button in the upper right corner of de Xco (+)open Library, then a drag Text view, put the code Turtle Rockback.

3.3 will Placeholderchange Joshua Tree National Park.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Turtle Rock")
                .font(.title)
            Text("Joshua Tree National Park")
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

Place adjust the layout view to meet the demand.

3.4 The location of view fontset .subheadline.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Turtle Rock")
                .font(.title)
            Text("Joshua Tree National Park")
                .font(.subheadline)
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

3.5 editing VStackinitialization method, in the view leadingalignment.

By default, stacksit will content centered along its axis, and provided a pitch appropriate to the context.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            Text("Joshua Tree National Park")
                .font(.subheadline)3
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

Next, we add another location to the right of the text view to display the state park is located.

3.6 In canvasthe hold down Command, click Joshua Tree National Park, then select Embed in HStack.

After 3.7 Location Added a text view, will be Placeholdermodified California, and then fontarranged .subheadline.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            HStack {
                Text("Joshua Tree National Park")
                    .font(.subheadline)
                Text("California")
                    .font(.subheadline)
            }
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

3.8 in the horizontal stackadd one Spacerto split and fixed Joshua Tree National Parkand Californiaso that they will share the entire width of the screen.

spacer It contains the deployable view, so that they all share the parent view of the space, not only its size is defined by its content.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            HStack {
                Text("Joshua Tree National Park")
                    .font(.subheadline)
                Spacer()
                Text("California")
                    .font(.subheadline)
            }
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

3.9 Finally, use .padding()this method to modify the landmark name and leave some space information.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            HStack {
                Text("Joshua Tree National Park")
                    .font(.subheadline)
                Spacer()
                Text("California")
                    .font(.subheadline)
            }
        }
        .padding()
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

4. Custom Image View

After get the name and location of view, we have to add a picture to the landmark.

There is no need to add a lot of code, just create a custom view, and then add to the picture masking, borders, and shading can be.

First, add pictures to the project asset catalogin.

4.1 project Resourcesto find the folder turtlerock.pngand drag it to asset catalogthe editor. Xcode will create a picture image set.

Next, create a new SwiftUIview to customize the image view.

4.2 Select File> New> FileOpen the Template Chooser. In User Interface, select SwiftUI View, then click Next. Name the file CircleImage.swift, and then click Create.

Now preparatory work has been completed.

4.3 Image(_:)initialization method will be replaced with a text view Turtle Rockpictures.

CircleImage.swift

import SwiftUI

struct CircleImage: View {
    var body: some View {
        Image("turtlerock")
    }
}

struct CircleImage_Preview: PreviewProvider {
    static var previews: some View {
        CircleImage()
    }
}
复制代码

4.4 calls .clipShape(Circle())trim an image into a circle.

CircleIt can be used as a mask's shape, can also strokeor fillform view.

CircleImage.swift

import SwiftUI

struct CircleImage: View {
    var body: some View {
        Image("turtlerock")
            .clipShape(Circle())
    }
}

struct CircleImage_Preview: PreviewProvider {
    static var previews: some View {
        CircleImage()
    }
}
复制代码

4.5 Create another gray stroke's circle, then as overlayadded to the picture, forming a picture frame.

CircleImage.swift

import SwiftUI

struct CircleImage: View {
    var body: some View {
        Image("turtlerock")
            .clipShape(Circle())
            .overlay(
                Circle().stroke(Color.gray, lineWidth: 4))
    }
}

struct CircleImage_Preview: PreviewProvider {
    static var previews: some View {
        CircleImage()
    }
}
复制代码

4.6 then the next to add a shadow radius of 10 point.

CircleImage.swift

import SwiftUI

struct CircleImage: View {
    var body: some View {
        Image("turtlerock")
            .clipShape(Circle())
            .overlay(
                Circle().stroke(Color.gray, lineWidth: 4))
            .shadow(radius: 10)
    }
}

struct CircleImage_Preview: PreviewProvider {
    static var previews: some View {
        CircleImage()
    }
}
复制代码

4.7 The color of the border changed to whitecomplete the image view.

CircleImage.swift

import SwiftUI

struct CircleImage: View {
    var body: some View {
        Image("turtlerock")
            .clipShape(Circle())
            .overlay(
                Circle().stroke(Color.white, lineWidth: 4))
            .shadow(radius: 10)
    }
}

struct CircleImage_Preview: PreviewProvider {
    static var previews: some View {
        CircleImage()
    }
}
复制代码

The use UIKit and SwiftUI

At this point, we are ready to create a map view, then use MapKitthe MKMapViewclass to render a map.

In SwiftUIuse, UIViewa subclass, you need to follow in other view packaging UIViewRepresentableprotocol SwiftUIview in. SwiftUIAnd it includes WatchKit, AppKitView similar agreements.

First, we can create a presentation MKMapViewto customize the view.

5.1 Select File> New> File, select iOSthe platform, select the SwiftUI Viewtemplate, and then click Next. The new file name MapView.swift, and then click Create.

5.2 to MapKitadd a importstatement to declare MapViewtype follows UIViewRepresentable.

Xcode can ignore the error, the next steps will be to solve these problems.

MapView.swift

import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {
    var body: some View {
        Text("Hello World")
    }
}

struct MapView_Preview: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}
复制代码

UIViewRepresentableProtocol need to implement two methods: makeUIView(context:)to create a MKMapView, updateUIView(_:context:)to view and respond to configuration changes.

5.3 with makeUIView(context:)alternative method bodyattribute, the method creates and returns a null MKMapView.

MapView.swift

import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {
	
	typealias UIViewType = MKMapView

    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        return MKMapView(frame: .zero)
    }
}

struct MapView_Preview: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}
复制代码

5.4 to achieve updateUIView(_:context:)a method, to set the coordinate map view, so that in Turtle Rockthe center.

MapView.swift

import SwiftUI
import MapKit

struct MapView : UIViewRepresentable {
    
    typealias UIViewType = MKMapView
    
    func makeUIView(context: UIViewRepresentableContext<MapView>) -> MKMapView {
        return MKMapView(frame: .zero)
    }
    
    func updateUIView(_ uiView: MKMapView, context: UIViewRepresentableContext<MapView>) {
        let coordinate = CLLocationCoordinate2D(
            latitude: 34.011286, longitude: -116.166868)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.setRegion(region, animated: true)
    }
}

struct MapView_Preview: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}
复制代码

When the preview in static modethe display only SwiftUIview. Because MKMapViewa UIViewsubclass, you need to switch to the real-time mode to see the map.

5.5 click Live Previewcan switch to Live Preview mode, sometimes used Try Againor Resumebuttons.

After a few moments, you will see Joshua Tree National Parkthe map, which is the Turtle Rockhometown.

6. Develop View details

Now that we have completed all the required components: name, location, pictures and maps round.

Continue to use the current tools, these components combine to become in line with final design details view.

6.1 In the project navigation, select the ContentView.swiftfile.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Text("Turtle Rock")
                .font(.title)
            HStack {
                Text("Joshua Tree National Park")
                    .font(.subheadline)
                Spacer()
                Text("California")
                    .font(.subheadline)
            }
        }
        .padding()
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

Of 6.2 prior to VStackembed another new VStackmedium.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

6.3 custom MapViewadded to the stacktop, using the frame(width:height:)method to set the MapViewsize.

If you specify only heightparameters, view automatically adjust the width of its contents. This section, MapViewexpands to fill all available space.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .frame(height: 300)

            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

6.4 Click the Live Previewbutton to see the rendering in combination view the map.

In this process, we can continue to edit view.

6.5 will be CircleImageadded to the stackmedium.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .frame(height: 300)

            CircleImage()

            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

6.6 In order to image viewlayout map viewthe top, we need to set the picture -130 pointsoffset, and fill from the bottom -130 points.

After the picture moves up to make room for the text.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .frame(height: 300)

            CircleImage()
                .offset(y: -130)
                .padding(.bottom, -130)

            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

6.7 externally VStackadding a base spacer, to push content to the top of the screen.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .frame(height: 300)

            CircleImage()
                .offset(y: -130)
                .padding(.bottom, -130)

            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()

            Spacer()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

6.8 Finally, in order to expand map content to the edge of the screen, you need to edgesIgnoringSafeArea(.top)add to the map view.

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            MapView()
                .edgesIgnoringSafeArea(.top)
                .frame(height: 300)

            CircleImage()
                .offset(y: -130)
                .padding(.bottom, -130)

            VStack(alignment: .leading) {
                Text("Turtle Rock")
                    .font(.title)
                HStack(alignment: .top) {
                    Text("Joshua Tree National Park")
                        .font(.subheadline)
                    Spacer()
                    Text("California")
                        .font(.subheadline)
                }
            }
            .padding()

            Spacer()
        }
    }
}

struct ContentView_Preview: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
复制代码

Reproduced in: https: //juejin.im/post/5cfa706f6fb9a07ee1691a46

Guess you like

Origin blog.csdn.net/weixin_34197488/article/details/91443407