没有textview的iphone键盘

jon*_*dep 6 iphone keyboard iphone-softkeyboard

是否可以在没有textview的iPhone应用程序中调出键盘?或者我必须有一个看不见的textview?

如果是这样,你如何以编程方式创建文本视图,然后调出键盘(用户不必点击文本视图)?我能找到的唯一例子是使用界面构建器..

kla*_*ter 9

显示键盘的唯一(有效)方法是使文本字段成为第一响应者.您可以通过调用becomeFirstResponder隐藏的文本字段来隐藏它并以编程方式使其成为第一响应者.

您可以通过执行类似的操作以编程方式创建UITextView(假设存在aRect和视图)

var textView = [[[UITextView alloc] initWithFrame:aRect] autorelease];
[view addSubview:textView];

[textView becomeFirstResponder];
Run Code Online (Sandbox Code Playgroud)


Kla*_*aas 5

UIKeyInput是你的朋友:

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..<text.endIndex.predecessor()]
            text = newText
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例。点击红色视图并查看 Xcode 控制台输出:

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)