The official document: developer.apple.com/documentati…

TextField is similar to UITextField in UIKit, which is used to implement the user’s input of text content.

Example code:

import SwiftUI

struct TextFieldPage: View {
    @State var content: String
    var body: some View {
        VStack {
            Text("You say:\(content)")
            
            TextField("Input",
                      text: $content,
                      onEditingChanged: { isEditing in
                        print("onEditingChanged::\(content)")
                      },
                      onCommit: {
                        print("onCommit::\(content)")
                      })
                .textFieldStyle(.roundedBorder)
                .padding()
        
        }
    }
}

struct TextFieldPage_Previews: PreviewProvider {
    static var previews: some View {
        TextFieldPage(content: "")}}Copy the code

TextField init parameter description:

  • OnEditingChanged: Triggers execution when the edit state changes, when the cursor appears in a TextFiled, or when the cursor leaves a TextFiled.
  • OnCommit: Executed at the end of editing, onCommit will trigger execution when we press Enter to close the keyboard.

Add create function to to-do list

Below we will achieve click the create button, pop up a page to add to-do items.

First we’ll add an add button at the bottom of the code listing project:

HStack {
    Button("Add to-do items") {
        popoverIsShow = true
    }
    .padding(.leading)    
    Spacer()
}
.frame(height: 44)
Copy the code

Then we create an AddPage:

import SwiftUI

struct AddPage: View {
    var body: some View {
        Text("Hello, OldBirds!")}}struct AddPage_Previews: PreviewProvider {
    static var previews: some View {
        AddPage()}}Copy the code

Let’s add a click event to the add to to-do button and pop up the AddPage when clicked:

Use popoverIsShow to control whether the page pops up or not.

After the jump is implemented, we need to improve the AddPage page. Here, we will simply implement an input box for entering task.

struct AddPage: View {
    @Binding var isPresented: Bool
    @State var task: String = ""
    var addItem: (String) - >Void

    var body: some View {
        NavigationView {
            VStack {
                HStack (alignment: .center){
                    Button("Cancel") {
                        isPresented = false
                    }.padding()

                    Spacer(a)Text("Add to-do items")
                        .padding()

                    Spacer(a)Button("Add") {
                        if task.count > 0 {
                            isPresented = false
                            addItem(task)
                        }
                    }
                    .foregroundColor(task.count > 0 ? Color.blue: Color.gray )
                    .padding()

                }.frame(height: 44)

                VStack {
                    Group {
                        TextField("Title", text: $task).padding()
                    }
                    .background(Color.white)
                    .cornerRadius(10)
                    .padding()
                }
                Spacer()
            }
            .edgesIgnoringSafeArea([.bottom])
            .background(Color("pageBgColor").edgesIgnoringSafeArea(.all))
            .navigationBarHidden(true)}}}Copy the code

So in AddPage, I’m going to cancel, and we’re just going to change isPresented = false, and we’re going to pass it externally. You can enter the name of your to-do item in the Enter button. When the length of the to-do’s name is greater than zero, we highlight the add button, click the highlight to close the page, and call back to addItem to pass the task back to the caller.

In MainPage, we modify the code as follows:

In addItem we create a new TodoItem and append it to listData.

Let’s see how it works.

The final code looks like this

MainPage.swift


import SwiftUI

struct TodoItem: Identifiable {
    var id: UUID = UUID(a)var task: String
    var imgName: String
}

struct MainPage: View {
    @State var isEditMode: EditMode = .inactive
    @State private var popoverIsShow: Bool = false
    
    @State var listData: [TodoItem] = [
        TodoItem(task: "Write a SwiftUI article", imgName: "pencil.circle"),
        TodoItem(task: "Watch a WWDC video.", imgName: "square.and.pencil"),
        TodoItem(task: "Order takeout.", imgName: "folder"),
        TodoItem(task: "Follow OldBirds public account", imgName: "link"),
        TodoItem(task: "Run 2 kilometers at 6:30.", imgName: "moon"),]var body: some View {
        NavigationView {
            VStack {
                List {
                    Section(header: Text("To Do")) {
                        ForEach(listData) { item in
                            HStack{
                                Image(systemName: item.imgName)
                                Text(item.task)
                            }
                        }
                        .onDelete(perform: deleteItem)
                        .onMove(perform: moveItem)
                    }
                    Section(header: Text("Other content")) {
                        Text("Hello World")
                    }
                }
                .toolbar {
                    Button(isEditMode.isEditing ? "Complete": "Edit") {
                        switch isEditMode {
                        case .active:
                            self.isEditMode = .inactive
                        case .inactive:
                            self.isEditMode = .active
                        default:
                            break
                        }
                    }
                }
                .environment(\.editMode, $isEditMode)
                .listStyle(GroupedListStyle())
                
                HStack {
                    Button("Add to-do items") {
                        popoverIsShow = true
                    }
                    .padding(.leading)
                    .sheet(isPresented: $popoverIsShow) {
                    } content: {
                        AddPage(isPresented: $popoverIsShow, addItem: addItem)
                    }
                    
                    Spacer()
                }
                .frame(height: 44)
            }
            .navigationBarTitle(Text("To Do list"))
        }
        .navigationViewStyle(.stack)
    }
    
    / / / add
    func addItem(task: String) {
        listData.append(TodoItem(task: task, imgName: "circle"))}/ / / move
    func moveItem(from source: IndexSet.to destination: Int) {
        listData.move(fromOffsets: source, toOffset: destination)
    }
    
    / / / deleted
    func deleteItem(at offsets: IndexSet) {
        listData.remove(atOffsets: offsets)
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        MainPage()}}Copy the code

AddPage.swift

//
// AddPage.swift
// swiftui-demo
//
// Created by mac on 2021/7/20.
//

import SwiftUI

struct AddPage: View {
    
    @Binding var isPresented: Bool
    
    @State var task: String = ""

    var addItem: (String) - >Void

    var body: some View {
        NavigationView {
            VStack {
                HStack (alignment: .center){
                    Button("Cancel") {
                        isPresented = false
                    }.padding()

                    Spacer(a)Text("Add to-do items")
                        .padding()

                    Spacer(a)Button("Add") {
                        if task.count > 0 {
                            isPresented = false
                            addItem(task)
                        }
                    }
                    .foregroundColor(task.count > 0 ? Color.blue: Color.gray )
                    .padding()

                }.frame(height: 44)

                VStack {
                    Group {
                        TextField("Title", text: $task).padding()
                    }
                    .background(Color.white)
                    .cornerRadius(10)
                    .padding()
                }
                Spacer()
            }
            .edgesIgnoringSafeArea([.bottom])
            .background(Color("pageBgColor").edgesIgnoringSafeArea(.all))
            .navigationBarHidden(true)}}}struct AddPage_Previews: PreviewProvider {
    static var previews: some View {
        AddPage(isPresented: .constant(true)) { value in}}}Copy the code