iphone keyboard without textview

后端 未结 4 1010
难免孤独
难免孤独 2020-12-15 01:22

is it possible to bring up the keyboard in an iphone app without a textview? or will i have to have an invisible textview?

if so, how do you programatically create a

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 01:49

    UIKeyInput is your friend:

    protocol KeyboardInputControlDelegate: class {
        func keyboardInputControl( keyboardInputControl:KeyboardInputControl, didPressKey key:Character)
    }
    
    class KeyboardInputControl: UIControl, UIKeyInput {
    
        // MARK: - properties
    
        weak var delegate: KeyboardInputControlDelegate?
    
        // MARK: - init
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            addTarget(self, action: Selector("onTouchUpInside:"), forControlEvents: .TouchUpInside)
        }
    
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        // MARK: - UIView
    
        override func canBecomeFirstResponder() -> Bool {
            return true
        }
    
        // MARK: - methods
    
        dynamic private func onTouchUpInside(sender: KeyboardInputControl) {
            becomeFirstResponder()
        }
    
        // MARK: - UIKeyInput
    
        var text:String = ""
    
        func hasText() -> Bool {
            return text.isEmpty
        }
    
        func insertText(text: String) {
            self.text = text
            for ch in text {
                delegate?.keyboardInputControl(self, didPressKey: ch)
            }
        }
    
        func deleteBackward() {
            if !text.isEmpty {
                let newText = text[text.startIndex..

    Example usage. Tap the red view and see the Xcode console output:

    class ViewController: UIViewController, KeyboardInputControlDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let kic = KeyboardInputControl(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
            kic.delegate = self
            kic.backgroundColor = UIColor.redColor()
            view.addSubview(kic)
        }
    
        func keyboardInputControl(keyboardInputControl: KeyboardInputControl, didPressKey key: Character) {
            println("Did press: \(key)")
        }
    }
    

提交回复
热议问题