2

所以我开始学习 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) {
    }
}
4

0 回答 0