如何使用Combine来跟踪UIViewRepresentable类中的UITextField变化?

时间:2019-10-18 01:40:54

标签: swift uitextfield swiftui uitextfielddelegate combine

我创建了一个自定义文本字段,我想利用Combine。为了在文本字段中的文本更改时得到通知,我目前使用自定义修饰符。它工作正常,但我希望此代码可以在CustomTextField结构中使用。

我的CustomTextField结构符合UIViewRepresentable。在此结构中,有一个名为Coordinator的NSObject类,它符合UITextFieldDelegate。

我已经在使用其他UITextField委托方法,但是找不到与我的自定义修饰符完全一样的方法。一些方法很接近,但是并没有完全按照我希望的方式表现。无论如何,我觉得最好将此新的自定义textFieldDidChange方法放在Coordinator类中。

这是我的自定义修饰符

private let textFieldDidChange = NotificationCenter.default
    .publisher(for: UITextField.textDidChangeNotification)
    .map { $0.object as! UITextField}


struct CustomModifer: ViewModifier {

     func body(content: Content) -> some View {
         content
             .tag(1)
             .onReceive(textFieldDidChange) { data in

                //do something

             }
    }
}

我的CustomTextField用于SwiftUI视图,并附加了我的自定义修饰符。只要文本字段发生更改,我就可以执行操作。修改器还使用Combine。它很好用,但是我不希望此功能采用修饰符的形式。我想在Coordinator类中使用它,以及UITextFieldDelegate方法。

这是我的CustomTextField

struct CustomTextField: UIViewRepresentable {

    var isFirstResponder: Bool = false
    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel

    func makeCoordinator() -> Coordinator {
        return Coordinator(authenticationViewModel: self._authenticationViewModel)
    }

    class Coordinator: NSObject, UITextFieldDelegate {

        var didBecomeFirstResponder = false
        @EnvironmentObject var authenticationViewModel: AuthenticationViewModel

        init(authenticationViewModel: EnvironmentObject<AuthenticationViewModel>)
        {
            self._authenticationViewModel = authenticationViewModel
        }

        // Limit the amount of characters that can be typed in the field
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

            let currentText = textField.text ?? ""
            guard let stringRange = Range(range, in: currentText) else { return false }
            let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
            return updatedText.count <= 14
        }

        /* I want to put my textFieldDidChange method right here */

        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * */


        func textFieldDidEndEditing(_ textField: UITextField) {

            textField.resignFirstResponder()
            textField.endEditing(true)
        }

    }

    func makeUIView(context: Context) -> UITextField {

        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.placeholder = context.coordinator.authenticationViewModel.placeholder
        textField.font = .systemFont(ofSize: 33, weight: .bold)
        textField.keyboardType = .numberPad

        return textField
    }

    func updateUIView(_ uiView: UITextField, context: Context) {

        let textField = uiView
        textField.text = self.authenticationViewModel.text
    }
}

struct CustomTextField_Previews: PreviewProvider {

    static var previews: some View {
        CustomTextField()
            .previewLayout(.fixed(width: 270, height: 55))
            .previewDisplayName("Custom Textfield")
            .previewDevice(.none)
    }
}

我一直在观看有关Combine的视频,我想在我正在开发的新应用中开始使用它。我确实认为在这种情况下使用是正确的做法,但仍然不确定如何实现这一目标。我真的很喜欢一个例子。

总结一下:

我想在我的Coordinator类中添加一个名为textFieldDidChange的函数,并且每次我的文本字段发生更改时都应该触发该函数。它必须利用Combine。

预先感谢

3 个答案:

答案 0 :(得分:2)

更新的答案

在查看了您的最新问题之后,我意识到我的原始答案可能需要进行一些清理。我已经将模型和协调器分解为一个类,尽管以我的示例为例,但这并不总是可行或理想的。如果模型和协调器不能相同,则不能依赖模型属性的didSet方法来更新textField。因此,我改为使用我们在模型中使用@Published变量免费获得的Combine发布者。

我们需要做的关键事情是:

  1. 通过使model.texttextField.text保持同步,从而使真理成为唯一来源

    1. 使用@Published属性包装器提供的发布者在textField.text发生更改时更新model.text

    2. .addTarget(:action:for)发生更改时,使用textField上的model.text方法来更新textfield.text

  2. 在模型更改时执行名为textDidChange的闭包。

(与#{1}相比,我更喜欢使用.addTarget,而不是经过NotificationCenter,因为它的代码更少,可以立即工作,并且UIKit的用户众所周知)。

以下是显示此工作方式的更新示例:

演示

import SwiftUI
import Combine

// Example view showing that `model.text` and `textField.text`
//     stay in sync with one another
struct CustomTextFieldDemo: View {
    @ObservedObject var model = Model()

    var body: some View {
        VStack {
            // The model's text can be used as a property
            Text("The text is \"\(model.text)\"")
            // or as a binding,
            TextField(model.placeholder, text: $model.text)
                .disableAutocorrection(true)
                .padding()
                .border(Color.black)
            // or the model itself can be passed to a CustomTextField
            CustomTextField().environmentObject(model)
                .padding()
                .border(Color.black)
        }
        .frame(height: 100)
        .padding()
    }
}

型号

class Model: ObservableObject {
    @Published var text = ""
    var placeholder = "Placeholder"
}

查看

struct CustomTextField: UIViewRepresentable {
    @EnvironmentObject var model: Model

    func makeCoordinator() -> CustomTextField.Coordinator {
        Coordinator(model: model)
    }

    func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
        let textField = UITextField()

        // Set the coordinator as the textField's delegate
        textField.delegate = context.coordinator

        // Set up textField's properties
        textField.text = context.coordinator.model.text
        textField.placeholder = context.coordinator.model.placeholder
        textField.autocorrectionType = .no

        // Update model.text when textField.text is changed
        textField.addTarget(context.coordinator,
                            action: #selector(context.coordinator.textFieldDidChange),
                            for: .editingChanged)

        // Update textField.text when model.text is changed
        // The map step is there because .assign(to:on:) complains
        //     if you try to assign a String to textField.text, which is a String?
        // Note that assigning textField.text with .assign(to:on:)
        //     does NOT trigger a UITextField.Event.editingChanged
        let sub = context.coordinator.model.$text.receive(on: RunLoop.main)
                         .map { Optional($0) }
                         .assign(to: \UITextField.text, on: textField)
        context.coordinator.subscribers.append(sub)

        // Become first responder
        textField.becomeFirstResponder()

        return textField
    }

    func updateUIView(_ textField: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
        // If something needs to happen when the view updates
    }
}

View.Coordinator

extension CustomTextField {
    class Coordinator: NSObject, UITextFieldDelegate, ObservableObject {
        @ObservedObject var model: Model
        var subscribers: [AnyCancellable] = []

        // Make subscriber which runs textDidChange closure whenever model.text changes
        init(model: Model) {
            self.model = model
            let sub = model.$text.receive(on: RunLoop.main).sink(receiveValue: textDidChange)
            subscribers.append(sub)
        }

        // Cancel subscribers when Coordinator is deinitialized
        deinit {
            for sub in subscribers {
                sub.cancel()
            }
        }

        // Any code that needs to be run when model.text changes
        var textDidChange: (String) -> Void = { text in
            print("Text changed to \"\(text)\"")
            // * * * * * * * * * * //
            // Put your code here  //
            // * * * * * * * * * * //
        }

        // Update model.text when textField.text is changed
        @objc func textFieldDidChange(_ textField: UITextField) {
            model.text = textField.text ?? ""
        }

        // Example UITextFieldDelegate method
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
    }
}

原始答案

听起来您有几个目标:

  1. 使用UITextField,以便您可以使用.becomeFirstResponder()之类的功能
  2. 文本更改时执行操作
  3. 通知其他SwiftUI视图文本已更改

我认为您可以使用单个模型类和UIViewRepresentable结构满足所有这些要求。我以这种方式构造代码的原因是,您有一个真实的来源(model.text),可以与其他采用StringBinding<String>的SwiftUI视图互换使用。

型号

class MyTextFieldModel: NSObject, UITextFieldDelegate, ObservableObject {
    // Must be weak, so that we don't have a strong reference cycle
    weak var textField: UITextField?

    // The @Published property wrapper just makes a Combine Publisher for the text
    @Published var text: String = "" {
        // If the model's text property changes, update the UITextField
        didSet {
            textField?.text = text
        }
    }

    // If the UITextField's text property changes, update the model
    @objc func textFieldDidChange() {
        text = textField?.text ?? ""

        // Put your code that needs to run on text change here
        print("Text changed to \"\(text)\"")
    }

    // Example UITextFieldDelegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

查看

struct MyTextField: UIViewRepresentable {
    @ObservedObject var model: MyTextFieldModel

    func makeUIView(context: UIViewRepresentableContext<MyTextField>) -> UITextField {
        let textField = UITextField()

        // Give the model a reference to textField
        model.textField = textField

        // Set the model as the textField's delegate
        textField.delegate = model

        // TextField setup
        textField.text = model.text
        textField.placeholder = "Type in this UITextField"

        // Call the model's textFieldDidChange() method on change
        textField.addTarget(model, action: #selector(model.textFieldDidChange), for: .editingChanged)

        // Become first responder
        textField.becomeFirstResponder()

        return textField
    }

    func updateUIView(_ textField: UITextField, context: UIViewRepresentableContext<MyTextField>) {
        // If something needs to happen when the view updates
    }
}

如果您不需要上面的#3,则可以替换

@ObservedObject var model: MyTextFieldModel

使用

@ObservedObject private var model = MyTextFieldModel()

演示

这是一个演示视图,显示了所有这些工作

struct MyTextFieldDemo: View {
    @ObservedObject var model = MyTextFieldModel()

    var body: some View {
        VStack {
            // The model's text can be used as a property
            Text("The text is \"\(model.text)\"")
            // or as a binding,
            TextField("Type in this TextField", text: $model.text)
                .padding()
                .border(Color.black)
            // but the model itself should only be used for one wrapped UITextField
            MyTextField(model: model)
                .padding()
                .border(Color.black)
        }
        .frame(height: 100)
        // Any view can subscribe to the model's text publisher
        .onReceive(model.$text) { text in
                print("I received the text \"\(text)\"")
        }

    }
}

答案 1 :(得分:1)

我还需要在SwiftUI中使用UITextField,所以我尝试了以下代码:

struct MyTextField: UIViewRepresentable {
  private var placeholder: String
  @Binding private var text: String
  private var textField = UITextField()

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

  func makeCoordinator() -> Coordinator {
    Coordinator(textField: self.textField, text: self._text)
  }

  func makeUIView(context: Context) -> UITextField {
    textField.placeholder = self.placeholder
    textField.font = UIFont.systemFont(ofSize: 20)
    return textField
  }

  func updateUIView(_ uiView: UITextField, context: Context) {
  }

  class Coordinator: NSObject {
    private var dispose = Set<AnyCancellable>()
    @Binding var text: String

    init(textField: UITextField, text: Binding<String>) {
      self._text = text
      super.init()

      NotificationCenter.default
        .publisher(for: UITextField.textDidChangeNotification, object: textField)
        .compactMap { $0.object as? UITextField }
        .compactMap { $0.text }
        .receive(on: RunLoop.main)
        .assign(to: \.text, on: self)
        .store(in: &dispose)
    }
  }
}

struct ContentView: View {
  @State var text: String = ""

  var body: some View {
    VStack {
      MyTextField("placeholder", text: self.$text).padding()
      Text(self.text).foregroundColor(.red).padding()
    }
  }
}

答案 2 :(得分:0)

我对您的要求有些困惑,因为您是在谈论UITextField和SwiftUI。

这样的事情呢?它不使用UITextField,而是使用SwiftUI的TextField对象。

只要您的TextField中的ContentView发生更改,此类都会通知您。

class CustomModifier: ObservableObject {
    var observedValue: String = "" {
        willSet(observedValue) {
            print(observedValue)
        }
    }
}

确保您在修饰符类上使用@ObservedObject,并且可以看到更改。

struct ContentView: View {
    @ObservedObject var modifier = CustomModifier()

    var body: some View {
        TextField("Input:", text: $modifier.observedValue)
    }
}

如果这与您的要求完全不符,那么我可以建议以下文章,这可能会有所帮助吗?

https://medium.com/@valv0/textfield-and-uiviewrepresentable-46a8d3ec48e2