我在项目中遇到如何处理 FocusState 的问题。
我的父视图在顶部创建了一个枚举:
enum RegistrationFocus: Hashable {
case username, password, confirmPassword, nameAndSurname, email, confirmEmail, phoneNumber
}
我的结构中有一个 focusState 变量
@FocusState var focus: RegistrationFocus?
我的子视图位于VStack中以显示所有视图。 (暂时只写了3个)
PersonalUserDetailsRow(title: "UserName", text: $registerModel.username, textContentType: .username, focus: $focus, focusfield: .username)
PersonalUserDetailsRow(title: "Password", text: $registerModel.password, textContentType: .newPassword, focus: $focus, focusfield: .password)
PersonalUserDetailsRow(title: "Confirm Password", text: $registerModel.confirmPassword, textContentType: .confirmPassword focus: $focus, focusfield: .confirmPassword)
我的 ChildView 看起来像这样:
struct PersonalUserDetailsRow: View {
var title: String
@Binding var text: String
let textContentType: UITextContentType
var focus: FocusState<RegistrationFocus?>.Binding
@State var focusField: RegistrationFocus?
var body: some View {
if textContentType == .newPassword {
SecureField(title, text: $text)
.padding(.top, 15)
.disableAutocorrection(true)
.textContentType(textContentType)
.focused(focus.projectedValue, equals: focusField)
Divider() .overlay(Color.black)
所以我的子视图确实包含
var focus: FocusState<RegistrationFocus?>.Binding
和 State focusField: RegistrationFocus?
但我不知道如何使用这两个。
当用户点击键盘上的返回键时,我想转到下一个文本字段。
我见过很多例子,人们在父视图中使用 2 个文本字段,我理解这些例子以及如何在使用 .focused(, equals:) 时移动文本字段。
但是我找不到任何如何使用子视图执行此操作的示例,尤其是使用此
.focused(focus.projectedValue, equals: focusField)
(如果它是正确的)。
我应该怎么做才能起作用? 我不断收到此错误:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions. with the above code
我尝试了这两个:
var focus: FocusState<RegistrationFocus?>.Binding
@State var focusField: RegistrationFocus?
@binding var focusField
不起作用。
我真的不想在我的父母视图中从子视图复制粘贴 textField 和 Divider() 7 次。我想学习如何在我的父母视图中使用 FocusState 的自定义视图。
更改
PersonalUserDetailsRow
以在设置字段值时设置下一个焦点字段:
struct PersonalUserDetailsRow: View {
var title: String
@Binding var text: String
// let textContentType: UITextContentType
@Binding var focus: RegistrationFocus?
let focused: RegistrationFocus
let nextFocused: RegistrationFocus
var body: some View {
// if textContentType == .newPassword {
SecureField(title, text: $text)
.onSubmit {
focus = nextFocused
}
.padding(.top, 15)
.disableAutocorrection(true)
// .textContentType(textContentType)
.focused($focus, equals: focused)
将您想要关注的下一个字段放入初始化程序中:
PersonalUserDetailsRow(title: "UserName", text: $registerModel.username, textContentType: .username, focus: $focus, focused: .username, nextFocused: .password)