swift playground UITextField spawns keyboard that is too big

帅比萌擦擦* 提交于 2019-12-12 07:52:54

问题


Swift in playground on Mac OS. When the user clicks in a UItextfield, a keyboard spawns but it is very large compared to the view and only the first few keys are available.

minimal example:

import UIKit
import PlaygroundSupport

class TesterViewController : UIViewController {
var testTextField : UITextField!
override func loadView() {
    let view = UIView()
    view.backgroundColor = .white

    testTextField = UITextField()
    testTextField.borderStyle = .roundedRect
    testTextField.text = ""
    view.addSubview(testTextField)
    testTextField.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
        testTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
        testTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
        ])

    self.view = view
    }
}
PlaygroundPage.current.liveView = TesterViewController()

screenshot


回答1:


I face the same issue. It seems as if Playground has a hard-coded screen size of 768x1024 (run UIScreen.main.bounds in the Playground) and shows the keyboard according to this size, independently of the live view's actual size.

The best workaround I came up with is to increase the size of the view controller so that it matches the keyboard:

let vc = TesterViewController()
vc.preferredContentSize = vc.view.frame.size // or a custom CGSize
PlaygroundPage.current.liveView = vc

Of course this makes the view larger than you might want it to be, so I only use this workaround when I really have to access the on-screen keyboard for testing.




回答2:


Instead this line

PlaygroundPage.current.liveView = MyViewController()

Write this

let window = UIWindow(frame: CGRect(x: 0,
                                    y: 0,
                                    width: 768,
                                    height: 1024))
let viewController = MyViewController()
window.rootViewController = viewController
window.makeKeyAndVisible()

PlaygroundPage.current.liveView = window

It works in Xcode 11



来源:https://stackoverflow.com/questions/46867712/swift-playground-uitextfield-spawns-keyboard-that-is-too-big

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!