0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

iOS14でTextFieldにdidBecomeFirstResponderを設定する

Last updated at Posted at 2022-12-08
CustomTextField.swift
struct CustomTextField: UIViewRepresentable {
  @Binding var text: String
  var font: UIFont = .init()
  var textAlignment: NSTextAlignment = .left

  var isFirstResponder: Bool

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

  func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
    let textField = UITextField(frame: .zero)
    textField.font = font
    textField.textAlignment = textAlignment
    textField.delegate = context.coordinator
    textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

    return textField
  }

  func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
    uiView.text = text

    if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
      uiView.becomeFirstResponder()
      context.coordinator.didBecomeFirstResponder = true
    }
  }
}

extension CustomTextField {
  func makeCoordinator() -> CustomTextField.Coordinator {
    Coordinator(text: $text)
  }

  class Coordinator: NSObject, UITextFieldDelegate {
    @Binding var text: String
    var didBecomeFirstResponder = false

    init(text: Binding<String>) {
      _text = text
    }

    func textFieldDidChangeSelection(_ textField: UITextField) {
      text = textField.text ?? ""
    }
  }
}

extension CustomTextField {
  public func font(_ font: UIFont) -> CustomTextField {
    var view = self
    view.font = font
    return view
  }

  public func textAlignment(_ alignment: NSTextAlignment) -> CustomTextField {
    var view = self
    view.textAlignment = alignment
    return view
  }
}
Content.swift
struct ContentView : View {
  @State var text: String = ""

  var body: some View {
    CustomTextField(text: $text, isFirstResponder: true)
      .borderStyle(.roundedRect)
      .frame(width: 200, height: 40)
      .background(Color.red)
  }
}

iOS15以降は@FocusStateを使う

参考にしたのはこちら

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?