首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在TextField中以编程方式自动聚焦SwiftUI

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

Stack Overflow用户
提问于 2019-10-09 19:29:02
回答 4查看 24.1K关注 0票数 33

我用一个模式把名字添加到一个列表中。当显示模态时,我希望自动对TextField进行聚焦,如下所示:

我还没有找到合适的解决方案。

为了做到这一点,已经在SwiftUI中实现了什么吗?

谢谢你的帮助。

代码语言:javascript
运行
复制
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()
        }
    }
EN

回答 4

Stack Overflow用户

发布于 2020-04-09 12:30:13

由于响应链不是通过SwiftUI来显示的,所以我们必须使用UIViewRepresentable来使用它。我已经做了一个与我们使用UIKit的方式类似的解决方案。

代码语言:javascript
运行
复制
 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()
       }
  }

}

你可以像这样使用这个组件..。

代码语言:javascript
运行
复制
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是为当前的textfield分配响应程序,而nextResponder是在当前textfield退出时做出第一个响应。

票数 23
EN

Stack Overflow用户

发布于 2020-10-26 22:55:04

SwiftUIX解

使用SwiftUIX非常容易,我很惊讶更多的人没有意识到这一点。

  1. 通过SwiftUIX安装快速包装管理器
  2. 在您的代码中,import SwiftUIX
  3. 现在,您可以使用CocoaTextField而不是TextField来使用.isFirstResponder(true)函数。
代码语言:javascript
运行
复制
CocoaTextField("Confirmation Code", text: $confirmationCode)
    .isFirstResponder(true)
票数 9
EN

Stack Overflow用户

发布于 2020-12-30 20:29:54

我认为SwiftUIX有很多有用的东西,但这仍然是您控制区域之外的代码,谁知道当SwiftUI 3.0发布时,糖的魔力会发生什么。请允许我介绍稍微升级的无聊UIKit解决方案,并对DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)进行合理的检查和升级。

代码语言:javascript
运行
复制
// 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)
    }
}

// ContentView.swift

代码语言:javascript
运行
复制
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)
      }
   }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58311022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档