1. FocusState 输入文本添加焦点状态
1.1 实现
/// 输入文本焦点状态
struct FocusStateBootcamp: View {
// 使用枚举
enum OnboardingFields: Hashable{
case username
case password
}
//@FocusState private var usernameInFocus: Bool
@State private var username: String = ""
//@FocusState private var passwordInFocus: Bool
@State private var password: String = ""
// 声明变量
@FocusState private var fieldInFocus: OnboardingFields?
var body: some View {
VStack(spacing: 30){
TextField("Add your name here...", text: $username)
.focused($fieldInFocus, equals: .username)
//.focused($usernameInFocus)
.padding(.leading)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(Color.gray.brightness(0.3))
.cornerRadius(10)
// 安全输入文本
SecureField("Add your password here...", text: $password)
.focused($fieldInFocus, equals: .password)
//.focused($passwordInFocus)
.padding(.leading)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(Color.gray.brightness(0.3))
.cornerRadius(10)
//Button("Toggle Focus State") {
// usernameInFocus.toggle()
//}
Button("Sign up 🚀") {
//passwordInFocus.toggle()
let usernameIsValid = !username.isEmpty
let passwordIsValid = !password.isEmpty
if usernameIsValid && passwordIsValid{
print("Sign up")
fieldInFocus = nil
}else if usernameIsValid{
//usernameInFocus = false
//passwordInFocus = true
fieldInFocus = .password
}else {
//usernameInFocus = true
//passwordInFocus = false
fieldInFocus = .username
}
}
}
.padding(40)
// .onAppear {
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// self.usernameInFocus = true
// }
// }
}
}
1.2 效果图:
2. SubmitTextField 根据输入文本设置,修改输入键盘内容
2.1 实现
///根据输入文本设置,修改输入键盘内容 iOS 15 版本新操作功能
struct SubmitTextFieldBootcamp: View {
@State private var text: String = ""
var body: some View {
VStack {
TextField("Placeholder...", text: $text)
// 修改返回按键
.submitLabel(.route)
// 单击返回按钮时执行操作
.onSubmit {
print("Something to the console!")
}
TextField("Placeholder...", text: $text)
// 修改返回按键
.submitLabel(.next)
// 单击返回按钮时执行操作
.onSubmit {
print("Something to the console!")
}
TextField("Placeholder...", text: $text)
// 修改返回按键
.submitLabel(.search)
// 单击返回按钮时执行操作
.onSubmit {
print("Something to the console!")
}
}
}
}
2.2 效果图: