SwiftUI_visionOS_Note

.onSubmit

May 9, 2024
1 min read|

As of iOS 15, we can use the new .submitLabel modifier to change the color and text of the submit button on the keyboard. Even more importantly, we can also use .onSubmit to run custom functions when users click on the submit button! These features were not available before iOS 15 in SwiftUI.

TextField("Placeholder...", text: $text)
	.onSubmit {
		print("Hello, World")
	}
swift

with .onSubmit , we can add a function to the enter button on the keyboard.

TextField(...)
	.submitLabel(.continue)
swift

with .submitLabel, we can label the enter

import SwiftUI
import RealityKit

struct ContentView: View {
    @State private var boxHeight: Float = 1.0
    @State private var boxEntity: ModelEntity?

    var body: some View {
        VStack {
            RealityView { content in
                if let boxEntity = boxEntity {
                    content.add(boxEntity)
                } else {
                    // Create the box entity only once
                    let box = ModelEntity(mesh: .generateBox(size: [1, boxHeight, 1]), materials: [SimpleMaterial(color: .red, isMetallic: false)])
                    self.boxEntity = box
                    content.add(box)
                }
            }
            .onUpdate { view in
                boxEntity?.scale = [1, boxHeight, 1]
            }

            Slider(value: $boxHeight, in: 0.1...3, step: 0.1)
        }
    }
}

#Preview(windowStyle: .automatic) {
    ContentView()
}
swift

Subscribe to our newsletter

Get the latest news and updates from our team