Custom TextField Menu Actions | SwiftUI

แชร์
ฝัง
  • เผยแพร่เมื่อ 12 พ.ย. 2024

ความคิดเห็น • 3

  • @Kavsoft
    @Kavsoft  7 วันที่ผ่านมา +2

    To make a TextField with the axis property functional,
    1. You need to change the UITextFieldDelegate to UITextViewDelegate.
    2. Change the below code,
    func textField(_ textField: UITextField, editMenuForCharactersIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu?
    to this:
    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu?
    3. Add these code block into the Coordinator,
    var originalDelegate: UITextViewDelegate?
    func textViewDidChangeSelection(_ textView: UITextView) {
    originalDelegate?.textViewDidChangeSelection?(textView)
    }
    func textViewDidChange(_ textView: UITextView) {
    originalDelegate?.textViewDidChange?(textView)
    }
    5. Change TextFieldAction callback from this:
    var action: (NSRange, UITextField) -> ()
    to this:
    var action: (NSRange, UITextView) -> ()
    6. Finally modify the makeUI view code block to this,
    DispatchQueue.main.async {
    if let textView = view.superview?.superview?.subviews.last?.subviews.first as? UITextView {
    context.coordinator.originalDelegate = textView.delegate
    textView.delegate = context.coordinator
    }
    }
    After making all these adjustments, the TextField with the axis property will function correctly.

  • @championfu4541
    @championfu4541 6 วันที่ผ่านมา

    Traversal to find a particular view is dangerous, because the internal view composition of each system version is inconsistent

    • @Kavsoft
      @Kavsoft  6 วันที่ผ่านมา

      Yes, that’s the reason I restricted the custom modifier to TextField only and prevented any view customizations on it. Without any view customizations (modifiers), it will always result in the same view. I also used the compostingGroup modifier to ensure the result!