Forum Xamarin.iOS

Potentially useful text input attached to keyboard - with source code

Tom-PrattTom-Pratt GBMember ✭✭

I was getting annoyed with trying to make table cells that expand and collapse as the user types in them. Despite having had it working in the past, on iOS 9 it was causing the table to jump around. So after spotting the AccessoryInputView option I thought this would be a nice easy way to capture text input in iOS. It turned out to be just as fiddly but I'd started and couldn't stop!

It's a bit like in a messaging app only that the text input only appears with the keyboard as opposed to always being pinned to the bottom of the screen. It's good for situations where you might want the user to click a button and then enter some text.

Use it in a view controller like this...

var textInputObject = new TextInputObject ();
View.AddSubview (textInputObject);

textInputObject.GetInput ("Hint", "Current Text", text => Label.Text = text);

The TextInputObject is a subclass of UITextField just so that it can be assigned an AccessoryInputView. In the subclass it inflates and manages and passes on responder duty to the actual view that the user types into. You add the TextInputObject to your view controllers view but it's really a dummy object so don't give it any size so it remains invisible.

The only slightly hacky thing is that iOS automatically adds a height constraint to the AccessoryInputView superview that would stop the text view growing and shrinking. So this is removed in the code.

If anyone wants to use it then please do, it seems to be working well so far. I think I'll use it in my current project so if you make any improvements then let me know or send on github! :D

https://github.com/Sylapse/AccessoryTextInput

Sign In or Register to comment.