简体   繁体   English

创建UITextView时,如何在Live View中显示的Swift Playgrounds(在Xcode上)的UI中隐藏键盘?

[英]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. 我已经创建了一个UITextView对象,当我在Live View与它进行交互时,键盘会出现在UI中,唯一输入文本的方法似乎是通过该键盘输入的。 Is this a recent change in Swift Playgrounds? 这是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. 您可以将手势识别器添加到超级视图,使用自定义关闭键盘方法分配动作,并在其中调用textField.resignFirstResponder()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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