1

I have created a UITextView object and when I interact with it in the Live View, the keyboard appears in the UI and the only way to enter text seems to be from that keyboard. Is this a recent change in Swift Playgrounds? Is there any way users can enter text from their physical keyboards?

Code:

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768))
textView.textColor = .green
textView.font = UIFont(name: "Courier", size: 22)
textView.backgroundColor = .black
mainView.addSubview(textView)

1 Answers1

0

You can add gesture recognizer to a superview, assign action with custom close keyboard method and call textField.resignFirstResponder() inside it.

Here is a quick example:

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    private var textView: UITextView?

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        textView = UITextView()

        if let textView = textView {
            textView.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            textView.text = "Hello World!"
            textView.textColor = .black

            view.addSubview(textView)
        }
        self.view = view
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
        self.view.addGestureRecognizer(tapGesture)
    }

    @objc func hideKeyboard() {
        textView?.resignFirstResponder()
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Anvar Azizov
  • 545
  • 1
  • 6
  • 9
  • Hi! Thanks for answering...I just experimented with it and the keyboard still appears in the UI and the textView doesn't take input from the physical keyboard :/ – Harshita Arora Mar 29 '18 at 15:01
  • Unfortunately, since Xcode 9, playground simulators no longer accept input from the physical keyboard. If you just want to hide the keyboard you can set the inputView of UITextView to UIView with an empty frame. – Anvar Azizov Mar 29 '18 at 15:08
  • Okay just tested. Setting the inputView to UiView with an empty frame hides the keyboard in the UI completely....but the UITextView still doesn't accept input form physical keyboard (as you mentioned). – Harshita Arora Mar 29 '18 at 15:14