テキストビューなしでiPhoneアプリでキーボードを表示することは可能ですか? または、目に見えないテキストビューが必要ですか?
もしそうなら、どのようにプログラムでテキストビューを作成し、キーボードを表示しますか (ユーザーがテキストビューをタップする必要はありません)。私が見つけることができる唯一の例は、インターフェースビルダーを使用しています..
テキストビューなしでiPhoneアプリでキーボードを表示することは可能ですか? または、目に見えないテキストビューが必要ですか?
もしそうなら、どのようにプログラムでテキストビューを作成し、キーボードを表示しますか (ユーザーがテキストビューをタップする必要はありません)。私が見つけることができる唯一の例は、インターフェースビルダーを使用しています..
キーボードを表示する唯一の(有効な)方法は、ファーストレスポンダーであるテキストフィールドを持つことです。becomeFirstResponder非表示のテキストフィールドを呼び出すことで、プログラムで非表示にしてファーストレスポンダーにすることができます。
このようなことを行うことで、プログラムでUITextViewを作成できます(aRectとviewが存在すると仮定します)
var textView = [[[UITextView alloc] initWithFrame:aRect] autorelease];
[view addSubview:textView];
[textView becomeFirstResponder];
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)")
}
}
After some more digging, I found this. It's unofficial, but I bet it works.
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];
このような仕組みは、NSNotificationCenterパブリッシュ/サブスクライブ モデルを介して行われます。最初に を使用する必要があり、次にこれaddObserver:selector:name:object:を試すことができます:
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:NSTextDidBeginEditingNotification object:self]];
しかし、キーボード入力文字の値を取得するために、どの通知を受け取るか、または登録する必要があるかはわかりません。幸運と幸せなハッキング:)