(For beginners) Swift UI view element collection

This is a collection of common view elements in SwiftUI. For beginners who have just started learning SwiftUI.

[Basic format of SwiftUI view](#swiftui-Basic format of view)

[Variable type](#Variable type)

Preview (#Preview)

[Starting point](# Starting point)

[New in iOS 14](New in # ios-14-)

[Character](# character)

[Image](# image)

Table

Navigations

To show the user a different view to perform an action (#To show a different view to the user to perform an action)

[Tab Bar](# Tab Bar)

[Choose one value from specified options](#Select one value from specified options)

[Display multiple elements on screen](#Display multiple elements on screen)

Alert / Action Sheet (#Alert--Action Sheet)

[View modifiers](#view modifiers)

UIKit + SwiftUI

What's new in iOS 14

TextEditor ColorPicker ToolbarItem
View and edit long text Allows you to choose a color. Display the item in the bar.
image image image
See code example Seecodeexample Seecodeexample
Map DisclosureGroup ProgressView
View annotated map Show and hide content Show progress
image image image
See code example Seecodeexample Seecodeexample
TextEditor DatePicker Sign in with Apple
View and edit long strings Select a date Sign in with Apple
image image image
See code example Seecodeexample Seecodeexample

letter

Text TextField SecureField
Display one string Editable text field Editable for password entry
image image image
See code example Seecodeexample Seecodeexample

image

Image (Local file) Image (SFSymbol)
Display image Display system image
image image
See code example Seecodeexample

Table

List ForEach Form
image image image
See code example Seecodeexample Seecodeexample

Navigations

NavigationView
Embed your own View in the navigation view
image
See code example

To perform an action / to show the user another view

Button NavigationLink View sheet
Click to perform action Click to move to another view View view sheet
image image image
See code example Seecodeexample SeecodeexampleSeecodeexample

Tab bar

TabView
Show tab bar at the bottom of the screen
image
See code example

Select one value from the specified options

Toggle Picker
User turns on feature/Allow to turn off Select one value from the specified options
image image
See code example Seecodeexample

Display multiple elements on the screen

Multiple of the above views can be combined and displayed in one view.

HStack VStack Form
Horizontal placement Vertical placement Login form example
image image image
See code example Seecodeexample Seecodeexample
ZStack
Depth arrangement (front and back)
image
See code example

Alert / action sheet

Alert ActionSheet
Show alert window Show action sheet at the bottom of the screen
image image
See code exampleSeecodeexample Seecodeexample

ViewModifier View Modifier

You can use the view modifier to change the appearance of the view.

Example:

Image(systemName: "wand.and.stars")
    .font(.largeTitle)
    .foregroundColor(.blue)

Below is a list of common view modifiers:

Variable name how to use
.font Characters and sci-fi symbols(SF Symbol)Change the font size of the image
.frame Resize displayed objects
.padding() Add space around the object
.foregroundColor(.blue) Change the color of the object
.onAppear Actions to take when the view is displayed on the screen
.onTapGesture Take action when the user taps the view

UIKit + SwiftUI

UIHostingController

You can also use the UIHostingController to display the Swift UI view inside the UIKit view.

let swiftuiView = Map_Example()
let uiKitViewController = UIHostingController(rootView: swiftuiView)
self.present(uiKitViewController, animated: true, completion: nil)

UIViewControllerRepresentable

SwiftUI is a new framework, so it lacks some of the feature UIKit. In order to take advantage of the Sora feature UIKit, you must use UIViewControllerRepresentable.

QuickLookView PhotoPickerView MailComposeView
Preview file contents Photo picker Email composer
image image
See code example Seecodeexample Seecodeexample
TextMessageComposerView SafariView DocumentPicker
Text message composer Web display Document picker
image image
See code example Seecodeexample Seecodeexample

Basic format of SwiftUI view

The basic structure of the SwiftUI view is:

import SwiftUI

struct TextField_Example: View {
    
    //variable
    
    var body: some View {
        
        //UI component
        //Text, Image, Form, VStack, List, ...
        
    }
    
}

In the var body: some View section, enter the view code.

In the sample code provided on this web page, you need to pay attention to the content inside the body code block.

Declare variables in the // Variables section.

Variable type

As you may have noticed, SwiftUI has a number of types of variables. Below are two of the most commonly used variable types.

@State

struct ButtonSheet_Example: View {

    @State var showAnotherView: Bool = false
    
    var body: some View {
        
        Button(action: {
            self.showAnotherView = true
        }, label: {
            Text("Show another view")
        })
        .sheet(isPresented: $showAnotherView, content: {
            AnotherView(textContent: "Hello World.")
        })
        
    }
}

You can affect the look of your view by changing the value of @State.

For example, if showAnotherView is set to true somewhere in the program, the view ʻAnotherView` will be displayed.

When using the @State variable in your program, you may need to prepend the$symbol to the variable name. That way, you can have the view monitor the variable (and update the view's content if the variable changes).

You can initialize the value of the @ State variable in three ways:

  1. @State var showAnotherView: Bool = false
  2. You can initialize the variable by initializing the view ButtonSheet_Example. ButtonSheet_Example (showAnotherView: true)
  3. Variables can be initialized in the ʻinit` function:
struct ButtonSheet_Example: View {

    @State var showAnotherView: Bool
    
    init(...) {
        self.showAnotherView = .init(initialValue: false)
    }
    
    var body: some View {
        // TODO
    }
    
}

Normal variable

Regular variables are used to store values. Updating the canonical variables does not affect the appearance of the program.

struct ButtonSheet_Example: View {

    var userTappedButton: () -> Void
    
    var body: some View {
        
        Button(action: {
            self.userTappedButton()
        }, label: {
            Text("Show another view")
        })
        
    }
}

preview

Xcode allows you to directly preview the changes you've made to your Swift UI file. The preview is declared as follows.

struct TextField_Example_Previews: PreviewProvider {
    static var previews: some View {
        TextField_Example(textEntered: "SwiftUI_Components-Library")
    }
}

You can initialize the Swift UI display in static var previews: some View. Click the Resume button to the right of the X code to see a preview.

Starting point

We recommend that you create a new Xcode project and choose to use the SwiftUI App. This will allow you to try out the above components in your practice project.

There is also a good article written by takoikatakotako, so I recommend you to read it.

Swift UI 100 knocks

⭐️

Github web page

Visit this web page to see a list of my published Qiita articles by category.

Recommended Posts

(For beginners) Swift UI view element collection
[Swift] Try using Collection View
[Swift UI] Use Map view
[Swift 5] Implement UI for review function
Customize View with View Modifier in Swift UI
[Swift / For beginners] Write smartly with type inference
Swift UI 100 knocks
Kantai Collection Java # 1 Classes and Objects [For Beginners]
A collection of simple questions for Java beginners
Swift extension collection
Incorporate View created with Swift UI into ViewController
[For beginners] Let's be able to coat like Swift!
Swift UI TextView placeholder
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
Starting with Swift Swift UI
Scraping for beginners (Ruby)