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 textview and then bring up the keyboard (without the user having to tap the textview)? the only examples i can find use interface builder..
The only (valid) way to show the keyboard is to have a textfield that is first responder.
You can hide it and make it first responder programmatically by calling becomeFirstResponder
on the hidden textfield.
You can create a UITextView programmatically by doing something like this (assume aRect and view exist)
var textView = [[[UITextView alloc] initWithFrame:aRect] autorelease];
[view addSubview:textView];
[textView becomeFirstResponder];
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..<text.endIndex.predecessor()]
text = newText
}
}
}
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)")
}
}
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With