如何将inputView与SwiftUI TextField结合使用?

时间:2020-06-14 20:58:16

标签: swift swiftui uitextfield inputview uiinputviewcontroller

因此,我开始学习Swift,并决定使用SwiftUI编写我的第一个应用程序。我想使用自定义应用内键盘(另一个SwiftUI视图)来简化我的应用的使用。但是我不知道该怎么做,因为我是菜鸟,正在努力寻找在线示例。

我发现的信息建议使用UIViewRepresentable将UITextField导入到我的项目中-尽管可以这样做,但我不知道如何将SwiftUI视图传递给它用作inputView。

任何帮助将不胜感激-如果有人可以提供详细的示例代码,那将真正有帮助。

如果有帮助,我的代码在下面...

ContentView.swift中的SwiftUI视图

struct SecondView: View {
    var body: some View {
        VStack {
            CustomTextField(defaultText: "ENTER PLACEHOLDER TEXT HERE")
        }
    }
}

// This is the view I would like to use as the inputView for the text field
struct KeyPad: View {
    @State var selectedKeyPad: [row]
    @State var screenDivider: CGFloat

    var body: some View {
    <code omitted for brevity>
    }
}

我尝试与UIKit集成-存储在单独的swift文件中

import SwiftUI
import UIKit

class KeyboardViewController: UIInputViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = UIHostingController(rootView: KeyPad(selectedKeyPad: keyPad4, screenDivider: 2))
        addChild(vc)
        self.view.addSubview(vc.view)
        vc.view.translatesAutoresizingMaskIntoConstraints = false
        vc.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        vc.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        vc.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        vc.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }
}

class MyCustomTextField : UITextField, UITextFieldDelegate {
    override var inputViewController: UIInputViewController {
        get {
            return KeyboardViewController()
        }
    }
}

struct CustomTextField: UIViewRepresentable {
    var defaultText: String

    func makeUIView(context: Context) -> MyCustomTextField {
        let customTextField = MyCustomTextField()
        customTextField.placeholder = defaultText
        customTextField.textAlignment = .center
        return customTextField
    }

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

0 个答案:

没有答案