naz
naz

Reputation: 31

How do I use an inputView with a SwiftUI TextField?

So I've started to learn Swift and made the decision to write my first app using SwiftUI. I would like to use a custom in-app keyboard (another SwiftUI view) to make my app easier to use. But I can't figure out how to do this as i'm a noob and struggling to find examples online.

The information I have found suggests using UIViewRepresentable to import a UITextField in to my project - and whilst I can do this, I cannot figure out how to pass a SwiftUI view through to it for use as the inputView.

Any help would be greatly appreciated - and if someone can provide detailed example code then that would really help.

My code is below if it helps ...

SwiftUI Views in ContentView.swift

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>
    }
}

My attempt at integrating with UIKit - stored in a separate swift file

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) {
    }
}

Upvotes: 3

Views: 1021

Answers (0)

Related Questions