是否可以在没有textview的iPhone应用程序中调出键盘?或者我必须有一个看不见的文本视图?
如果是这样,你如何以编程方式创建文本视图然后调出键盘(用户不必点击textview)?我能找到的唯一例子是使用界面构建器..
答案 0 :(得分:8)
显示键盘的唯一(有效)方法是使文本字段成为第一响应者。
您可以隐藏它并通过在隐藏文本字段上调用becomeFirstResponder
以编程方式使其成为第一响应者。
您可以通过这样的方式以编程方式创建UITextView(假设存在aRect和视图)
var textView = [[[UITextView alloc] initWithFrame:aRect] autorelease];
[view addSubview:textView];
[textView becomeFirstResponder];
答案 1 :(得分:2)
经过多次挖掘后,我找到了this。这是非官方的,但我敢打赌它有效。
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];
答案 2 :(得分:1)
这些东西的工作方式是通过NSNotificationCenter发布/订阅模型。首先,您需要使用addObserver:selector:name:object:
,然后您可以尝试this:
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:NSTextDidBeginEditingNotification object:self]];
但我不确定你会得到或需要注册的通知,以获取键盘输入字符值。祝你好运和快乐的黑客行为:)
答案 3 :(得分:1)
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)")
}
}