xcode 在SwiftUI中以编程方式自动聚焦TextField

pokxtpni  于 2023-03-19  发布在  Swift
关注(0)|答案(5)|浏览(153)

我正在使用一个modal向列表中添加名称。当modal显示时,我希望自动聚焦TextField,如下所示:

我还没有找到合适的解决办法。
SwiftUI中是否已经实现了任何功能来实现这一点?
谢谢你的帮助。

var modal: some View {
        NavigationView{
            VStack{
                HStack{
                    Spacer()
                    TextField("Name", text: $inputText) // autofocus this!
                        .textFieldStyle(DefaultTextFieldStyle())
                        .padding()
                        .font(.system(size: 25))
                        // something like .focus() ??
                    Spacer()
                }
                Button(action: {
                    if self.inputText != ""{
                        self.players.append(Player(name: self.inputText))
                        self.inputText = ""
                        self.isModal = false
                    }
                }, label: {
                    HStack{
                        Text("Add \(inputText)")
                        Image(systemName: "plus")
                    }
                        .font(.system(size: 20))
                })
                    .padding()
                    .foregroundColor(.white)
                    .background(Color.blue)
                    .cornerRadius(10)
                Spacer()
            }
                .navigationBarTitle("New Player")
                .navigationBarItems(trailing: Button(action: {self.isModal=false}, label: {Text("Cancel").font(.system(size: 20))}))
                .padding()
        }
    }
gzjq41n4

gzjq41n41#

iOS 15操作系统

有一个名为@FocusState的新 Package 器,它控制键盘和焦点键盘(“aka”firstResponder)的状态。
注意️如果你想让它在初始时刻聚焦,你必须应用一个延迟。这是SwiftUI的一个已知bug。

成为第一响应者(专注)

如果对文本字段使用focused修饰符,则可以使它们成为焦点,例如,可以在代码中设置focusedField属性以使绑定的textField成为活动的:

放弃第一响应者(解散键盘)

或者通过将变量设置为nil来关闭键盘:

不要忘记观看WWDC 2021SwiftUI中的直接和反映焦点会议

iOS 13和14(以及15)

老旧但仍在使用:

简单的 Package 器结构-像本机一样工作:

注意根据注解中的要求添加了文本绑定支持

struct LegacyTextField: UIViewRepresentable {
    @Binding public var isFirstResponder: Bool
    @Binding public var text: String

    public var configuration = { (view: UITextField) in }

    public init(text: Binding<String>, isFirstResponder: Binding<Bool>, configuration: @escaping (UITextField) -> () = { _ in }) {
        self.configuration = configuration
        self._text = text
        self._isFirstResponder = isFirstResponder
    }

    public func makeUIView(context: Context) -> UITextField {
        let view = UITextField()
        view.addTarget(context.coordinator, action: #selector(Coordinator.textViewDidChange), for: .editingChanged)
        view.delegate = context.coordinator
        return view
    }

    public func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
        switch isFirstResponder {
        case true: uiView.becomeFirstResponder()
        case false: uiView.resignFirstResponder()
        }
    }

    public func makeCoordinator() -> Coordinator {
        Coordinator($text, isFirstResponder: $isFirstResponder)
    }

    public class Coordinator: NSObject, UITextFieldDelegate {
        var text: Binding<String>
        var isFirstResponder: Binding<Bool>

        init(_ text: Binding<String>, isFirstResponder: Binding<Bool>) {
            self.text = text
            self.isFirstResponder = isFirstResponder
        }

        @objc public func textViewDidChange(_ textField: UITextField) {
            self.text.wrappedValue = textField.text ?? ""
        }

        public func textFieldDidBeginEditing(_ textField: UITextField) {
            self.isFirstResponder.wrappedValue = true
        }

        public func textFieldDidEndEditing(_ textField: UITextField) {
            self.isFirstResponder.wrappedValue = false
        }
    }
}

用法:

struct ContentView: View {
    @State var text = ""
    @State var isFirstResponder = false

    var body: some View {
        LegacyTextField(text: $text, isFirstResponder: $isFirstResponder)
    }
}

额外🎁好处:完全可定制

LegacyTextField(text: $text, isFirstResponder: $isFirstResponder) {
    $0.textColor = .red
    $0.tintColor = .blue
}
nsc4cvqm

nsc4cvqm2#

由于响应器链不是通过SwiftUI来使用的,所以我们必须使用UIViewRepresentable来使用它。我已经制定了一个变通方案,它的工作方式与我们使用UIKit的方式类似。

struct CustomTextField: UIViewRepresentable {

   class Coordinator: NSObject, UITextFieldDelegate {

      @Binding var text: String
      @Binding var nextResponder : Bool?
      @Binding var isResponder : Bool?

      init(text: Binding<String>,nextResponder : Binding<Bool?> , isResponder : Binding<Bool?>) {
        _text = text
        _isResponder = isResponder
        _nextResponder = nextResponder
      }

      func textFieldDidChangeSelection(_ textField: UITextField) {
        text = textField.text ?? ""
      }
    
      func textFieldDidBeginEditing(_ textField: UITextField) {
         DispatchQueue.main.async {
             self.isResponder = true
         }
      }
    
      func textFieldDidEndEditing(_ textField: UITextField) {
         DispatchQueue.main.async {
             self.isResponder = false
             if self.nextResponder != nil {
                 self.nextResponder = true
             }
         }
      }
  }

  @Binding var text: String
  @Binding var nextResponder : Bool?
  @Binding var isResponder : Bool?

  var isSecured : Bool = false
  var keyboard : UIKeyboardType

  func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
      let textField = UITextField(frame: .zero)
      textField.isSecureTextEntry = isSecured
      textField.autocapitalizationType = .none
      textField.autocorrectionType = .no
      textField.keyboardType = keyboard
      textField.delegate = context.coordinator
      return textField
  }

  func makeCoordinator() -> CustomTextField.Coordinator {
      return Coordinator(text: $text, nextResponder: $nextResponder, isResponder: $isResponder)
  }

  func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
       uiView.text = text
       if isResponder ?? false {
           uiView.becomeFirstResponder()
       }
  }

}

您可以像这样使用此组件...

struct ContentView : View {

@State private var username =  ""
@State private var password =  ""

// set true , if you want to focus it initially, and set false if you want to focus it by tapping on it.
@State private var isUsernameFirstResponder : Bool? = true
@State private var isPasswordFirstResponder : Bool? =  false

  var body : some View {
    VStack(alignment: .center) {
        
        CustomTextField(text: $username,
                        nextResponder: $isPasswordFirstResponder,
                        isResponder: $isUsernameFirstResponder,
                        isSecured: false,
                        keyboard: .default)
        
        // assigning the next responder to nil , as this will be last textfield on the view.
        CustomTextField(text: $password,
                        nextResponder: .constant(nil),
                        isResponder: $isPasswordFirstResponder,
                        isSecured: true,
                        keyboard: .default)
    }
    .padding(.horizontal, 50)
  }
}

这里isResponder是将responder分配给当前文本域,nextResponder是在当前文本域放弃它时做出第一个响应。

xmjla07d

xmjla07d3#

SwiftUIX解决方案

使用SwiftUIX非常简单,我很惊讶更多的人没有意识到这一点。
1.通过Swift程序包管理器安装SwiftUIX。
1.在您的代码中,import SwiftUIX
1.现在,您可以使用CocoaTextField代替TextField来使用函数.isFirstResponder(true)

CocoaTextField("Confirmation Code", text: $confirmationCode)
    .isFirstResponder(true)
zlhcx6iw

zlhcx6iw4#

我认为SwiftUIX有很多方便的东西,但这仍然是你控制范围之外的代码,谁知道当SwiftUI 3.0出来时,糖魔法会发生什么。请允许我介绍一下无聊的UIKit解决方案,它通过合理的检查和升级的定时DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)进行了轻微升级

// AutoFocusTextField.swift

struct AutoFocusTextField: UIViewRepresentable {
    private let placeholder: String
    @Binding private var text: String
    private let onEditingChanged: ((_ focused: Bool) -> Void)?
    private let onCommit: (() -> Void)?
    
    init(_ placeholder: String, text: Binding<String>, onEditingChanged: ((_ focused: Bool) -> Void)? = nil, onCommit: (() -> Void)? = nil) {
        self.placeholder = placeholder
        _text = text
        self.onEditingChanged = onEditingChanged
        self.onCommit = onCommit
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIView(context: UIViewRepresentableContext<AutoFocusTextField>) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.placeholder = placeholder
        return textField
    }
    
    func updateUIView(_ uiView: UITextField, context:
                        UIViewRepresentableContext<AutoFocusTextField>) {
        uiView.text = text
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // needed for modal view to show completely before aufo-focus to avoid crashes
            if uiView.window != nil, !uiView.isFirstResponder {
                uiView.becomeFirstResponder()
            }
        }
    }
    
    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: AutoFocusTextField
        
        init(_ autoFocusTextField: AutoFocusTextField) {
            self.parent = autoFocusTextField
        }
        
        func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }
        
        func textFieldDidEndEditing(_ textField: UITextField) {
            parent.onEditingChanged?(false)
        }
        
        func textFieldDidBeginEditing(_ textField: UITextField) {
            parent.onEditingChanged?(true)
        }
        
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            parent.onCommit?()
            return true
        }
    }
}

 //   SearchBarView.swift


struct SearchBarView: View {
    @Binding private var searchText: String
    @State private var showCancelButton = false
    private var shouldShowOwnCancelButton = true
    private let onEditingChanged: ((Bool) -> Void)?
    private let onCommit: (() -> Void)?
    @Binding private var shouldAutoFocus: Bool
    
    init(searchText: Binding<String>,
         shouldShowOwnCancelButton: Bool = true,
         shouldAutofocus: Binding<Bool> = .constant(false),
         onEditingChanged: ((Bool) -> Void)? = nil,
         onCommit: (() -> Void)? = nil) {
        _searchText = searchText
        self.shouldShowOwnCancelButton = shouldShowOwnCancelButton
        self.onEditingChanged = onEditingChanged
        _shouldAutoFocus = shouldAutofocus
        self.onCommit = onCommit
    }
    
    var body: some View {
        HStack {
            HStack(spacing: 6) {
                Image(systemName: "magnifyingglass")
                    .foregroundColor(.gray500)
                    .font(Font.subHeadline)
                    .opacity(1)
                
                if shouldAutoFocus {
                    AutoFocusTextField("Search", text: $searchText) { focused in
                        self.onEditingChanged?(focused)
                        self.showCancelButton.toggle()
                    }
                    .foregroundColor(.gray600)
                    .font(Font.body)
                } else {
                    TextField("Search", text: $searchText, onEditingChanged: { focused in
                        self.onEditingChanged?(focused)
                        self.showCancelButton.toggle()
                    }, onCommit: {
                        print("onCommit")
                    }).foregroundColor(.gray600)
                    .font(Font.body)
                }
                
                Button(action: {
                    self.searchText = ""
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundColor(.gray500)
                        .opacity(searchText == "" ? 0 : 1)
                }.padding(4)
            }.padding([.leading, .trailing], 8)
            .frame(height: 36)
            .background(Color.gray300.opacity(0.6))
            .cornerRadius(5)
            
            if shouldShowOwnCancelButton && showCancelButton  {
                Button("Cancel") {
                    UIApplication.shared.endEditing(true) // this must be placed before the other commands here
                    self.searchText = ""
                    self.showCancelButton = false
                }
                .foregroundColor(Color(.systemBlue))
            }
        }
    }
}

#if DEBUG
struct SearchBarView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            SearchBarView(searchText: .constant("Art"))
                .environment(\.colorScheme, .light)
            
            SearchBarView(searchText: .constant("Test"))
                .environment(\.colorScheme, .dark)
        }
    }
}
#endif

// MARK: Helpers

extension UIApplication {
    func endEditing(_ force: Bool) {
        self.windows
            .filter{$0.isKeyWindow}
            .first?
            .endEditing(force)
    }
}

//内容视图.swift

class SearchVM: ObservableObject {
    @Published var searchQuery: String = ""
  ...
}

struct ContentView: View {
  @State private var shouldAutofocus = true
  @StateObject private var viewModel = SearchVM()
  
   var body: some View {
      VStack {
          SearchBarView(searchText: $query, shouldShowOwnCancelButton: false, shouldAutofocus: $shouldAutofocus)
      }
   }
}
sdnqo3pr

sdnqo3pr5#

对于macOS 13,有一个不需要延迟的新修改器。目前,在iOS 16上不起作用。

VStack {
    TextField(...)
        .focused($focusedField, equals: .firstField)
    TextField(...)
        .focused($focusedField, equals: .secondField)
}.defaultFocus($focusedField, .secondField) // <== Here

Apple Documentation: defaultFocus()

相关问题