SwiftUI is a very simple and innovative approach to building user interfaces across all Apple device platforms using Swift’s power. With SwiftUI, developers can build user interfaces for all Apple devices using just a set of tools and apis. SwiftUI uses the declarative Swift syntax that is easy to read and write, and works seamlessly with the new Xcode design tools to keep your code and design in perfect sync. SwiftUI automatically supports dynamic typing, dark mode, localization and accessibility, and your SwiftUI code will be the most powerful UI code you’ve ever written.

The target

Get to know SwfitUI quickly.

Result: Implement a list. Click item of the list to jump to the corresponding details.

This article is compiled here according to the official Apple tutorial

First, remember how to implement it in UIKit:

  1. Create a controller with Navigation to lay out and Push the next page.
  2. Add UITableView and implement two proxy methods of UITableView to display the list.
  3. Create UITableViewCell, layout UILabel and UIImageView.
  4. Create details page, layout map, three UIlabel.
  5. Push details in the UITableViewDelegate’s proxy method.

This is too simple and too familiar for iOS development, but a lot of the code is tedious, control creation, layout, etc. It was simple, but tedious, and wasted a lot of time that should have been spent on business.

How do you do that in SwiftUI?

Before you implement it, take a look at the components you need, roughly divided by purpose into basic components, layout components, and functional components, as well as the new features that XCode11 offers.

The required components

Based on the component

  • Text is used to display Text just like UILabel in UIKit

  • Image is used to display images just like UIImageView in UIKit

  • Spacer is used to fill in the blanks

Layout of the components

  • VStack Vertically stacked components

  • HStack Horizontal components

  • List is used to display lists just like UITableView in UIKit

Functional component

  • NavigationViewThe display navigation bar is similar toUINavigationBar
  • NavigationButtonSimilar to thepushViewController:methods

XCode11 related features

preview

See changes made to the page in real time

  • Static preview is the default for pure SwiftUI.

    Click the Resume button to preview the serial port.

    If no preview window is displayed, open it as shown below

  • When preview contains UIView subclass views, you need to turn on constant preview

Click to switch between constant preview and static preview

Drag and drop

You can add a component and set its properties by clicking the command key and the mouse.

Code implementation

Create a list of
struct LandmarkList : View {
    var body: some View {
      // Customize the display
        List(0 ..< 5) { item in
            Text("hello")
                .font(.title)
        }
    }
}
Copy the code

Using the List component, you can quickly create sliding lists without setting up proxies or implementing protocol methods to achieve a similar effect to UITableView in UIKit.

Text is used to display Text, and.font is used to set the font size. We put it in the List, it’s the Item of the List.

Effect:

Find the resource files from the project Resources folder and import the project, which contains JSON data, images, and so on. Swift and landmark. swift in the Models folder are also introduced, which are primarily for component Data and Models and are not the focus of this article. And we’re going to use that data.

To create the Item

This step in UIKit is like customizing UITableViewCell, which requires adding an image and a text to it.

In SwiftUI, there is no concept of UITableViewCell. When you need to display a line, you only need to use the HStack component. The HStack component is a composite component that can hold Text, Image, and other components.

Create LandmarkRow

struct LandmarkRow : View {
    var landmark: Landmark
    
    var body: some View {
        HStack {
            landmark.image(forSize: 50)
            Text(landmark.name)
        }
    }
}
Copy the code

Landmark. Image (forSize: 50) This method returns an image of the specified size

Text Displays the landmark name.

HStack displays images and text on a single line, configured in a default format.

Effect:

Take it into the list created in the first step and import the data.

struct LandmarkList : View {
    var body: some View {        
        List(landmarkData) { landmark in
            LandmarkRow(landmark: landmark)
        }   
    }
}
Copy the code

Effect:

The list is already displayed.

Think about all the code in UIKit, isn’t that cool?

Create details page

From the renderings, you can see that the detail page has a map, a circular picture, several words showing place names and locations.

In terms of layout, the bottom two horizontal text can be placed in the horizontal component, and then placed in the vertical component with the header text.

Maps, pictures, and horizontal components are grouped together in vertical components.

Create map module:

struct MapView : UIViewRepresentable {
    
    var coordinate: CLLocationCoordinate2D
    
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
    
    func updateUIView(_ view: MKMapView, context: Context) {
        let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)}}Copy the code

To add non-Swiftui components to SwiftUI, you need to follow the UIViewRepresentable protocol and implement protocol methods.

Create rounded image:

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

Create details page

struct LandMarkDetail : View {
    var landmark : Landmark
    
    var body: some View {
        VStack {
            MapView(coordinate: landmark.locationCoordinate).frame(height: 300)
            CircleImage(image: landmark.image(forSize: 250))
                .offset(y: -130)
                .padding(.bottom, -130)
            
          	// Three characters
            VStack(alignment: .leading) {
                Text(landmark.name)
                    .font(.title)
              // The following two words
                HStack {
                    Text(landmark.park)
                        .font(.subheadline)
                    Spacer(a)Text(landmark.state)
                        .font(.subheadline)
                }
                }
                .padding()
            Spacer()}}}Copy the code

VStack vertical assembly, which contains MapView and CircleImage and VStack.

The VStack contains the title text and the HStack.

The HStack contains two text components that are placed horizontally.

Effect:

Realize the jump

The above has respectively implemented the list page and details page, the following implementation of the jump.

To Push UIKit you need to create a UINavigationController, to display the navigation bar you need to set the UINavigationBar, to jump you need to call pushViewController: in the UITableView’s proxy method.

Modify the list created above:

struct LandmarkList : View {
    var body: some View {
        NavigationView {
            List(landmarkData) { landmark in
                NavigationButton(destination: LandmarkDetail(landmark: landmark)) {
                    LandmarkRow(landmark: landmark)
                 }
                }
                .navigationBarTitle(Text("Landmarks"), displayMode: .inline)
        }
    }
}
Copy the code

The NavigationView component is similar to the UINavigationBar and allows you to set the navigation bar title and mode.

NavigationButton can bind the jump method directly to the list display, making the logic clearer.

conclusion

Those of you who have read about Flutter may be quick to accept this.

Those of you who have not read about Flutter need to change your thinking about page layout.

SwiftUI is a great boon for iOS developers. After all, it is 9012 years old and still using such a primitive layout in UIKit.

SwiftUI needs iOS13 or above, but at present, the company’s APP development will support some old version of the system, and also need to use UIKit. Full SwiftUI use is expected to take some time. After all, there are plenty of companies that don’t use Swift.

SwiftUI official Tutorial

Xcode11 beta download