简体   繁体   中英

How can I hide the keyboard in the UI in Swift Playgrounds (on Xcode) that appears in the Live View when I create a UITextView?

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM