6

是否可以在没有文本视图的情况下在 iphone 应用程序中调出键盘?还是我必须有一个不可见的文本视图?

如果是这样,您如何以编程方式创建一个文本视图,然后调出键盘(无需用户点击文本视图)?我能找到的唯一示例使用界面生成器..

4

4 回答 4

10

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

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

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

[textView becomeFirstResponder];
于 2009-09-24T15:01:39.927 回答
4

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
        }
    }
}

示例用法。点击红色视图并查看 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)")
    }
}
于 2015-09-16T12:00:49.860 回答
2

经过一番挖掘,我发现了这个。这是非官方的,但我敢打赌它有效。

UIKeyboard *keyboard = [[[UIKeyboard alloc] initWithFrame: CGRectMake(0.0f, contentRect.size.height - 216.0f, contentRect.size.width, 216.0f)] autorelease];
        [keyboard setReturnKeyEnabled:NO];
        [keyboard setTapDelegate:editingTextView];
        [inputView addSubview:keyboard];
于 2009-09-24T16:30:14.013 回答
1

这些东西的工作方式是通过NSNotificationCenter发布/订阅模型。首先你需要使用addObserver:selector:name:object:,然后你可以尝试这样

[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:NSTextDidBeginEditingNotification object:self]];

但我不确定您会收到什么通知,或者需要注册哪些通知才能让键盘输入字符值。祝你好运,黑客愉快:)

于 2009-09-24T15:11:47.867 回答