Swift UI Get Started

Get Started with Swift UI

Swift UI is newly supported from XCode11.

  • View creation is by Code
  • Can preview with XCode for each View

Start Swift UI Project

We need to select Swift UI support when we create App project

Default files

File nameDescription
AppDelegatge.swiftSame as previous app file (but methods are totally different
Manage app
SceneDelegate.swiftManage window, viewcontroller, view etc… Launching app controller
Assets.xcassetsAsset catalogue
LaunchScreen.storyboardLaunch App screen. Start App View
Info.plistApplication configuration. Set property for iOS app
Preview ContentAnother asset catalogue
Stackoverflow link
ContentView.swiftFirst View, this view is registered by SceneDelegate.swift

Recommend Directory Structure

From Apple Samples, we can consider following directory structure

Project
|- Models                : Data Model(Struct, Class)
|- Supporting Views      : SubViews Component Level View
|- Resources             : Same as general iOS app(Save resources)
|- AppDelegate.swift

Let’s check default codes

SceneDelegate.swift

This is part of codes

// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()

// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
  let window = UIWindow(windowScene: windowScene)
  window.rootViewController = UIHostingController(rootView: contentView)
  self.window = window
  window.makeKeyAndVisible()
}

Create ContentView object and registered

ContentView.swift

import SwiftUI

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

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

import SwiftUI is for Swift UI. This is required

View is struct.

body is actual UI code, this contains all View code in View.

In this example, add Text

ContentView_Previews is for Preview not this code, you can see preview “Resume” button

You can see preview

This is an example

iOS
スポンサーリンク
Professional Programmer2

コメント