inputaccessoryview not showing (StoryBoard) - ios

I have been trying to incorporate a UIView/Toolbar above my keyboard but have had no luck. When I added a toolbar it was scrambled so thus I need to put it into a UIView but the UIView does not want to appear above the keyboard. Code Below:
My Header:
#property (nonatomic, Strong) IBOutlet UITextView *textView;
#property (nonatomic, strong) IBOutlet UIToolbar *TitleBar;
#property (nonatomic, weak) IBOutlet UIView *AddView;
The ViewDidLoad:
- (void)viewDidLoad
{
// observe keyboard hide and show notifications to resize the text view appropriately
/*[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
*/
if ([self respondsToSelector:#selector(setNeedsStatusBarAppearanceUpdate)]) {
// iOS 7
[self performSelector:#selector(setNeedsStatusBarAppearanceUpdate)];
} else {
// iOS 6
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
self.attributionTitle.delegate = self;
self.attribution.delegate = self;
textView.scrollEnabled = YES;
// quoteText.layer.borderColor = [UIColor blackColor].CGColor;
// quoteText.layer.borderWidth = 1.0f;
// textView.delegate = self; // code or in IB
[textView becomeFirstResponder];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
The textViewDidBeginEditing:
-(void)textViewDidBeginEditing:(UITextView *)textView
{
self.textView.inputAccessoryView = self.AddView;
}
Here is to show the UIView is connected:

I added the textView.inputAccessoryView = AddView;to the ViewDidLoadthen deleted the view from my storyboard and remade it. Lastly I added the UIView to the bottom black bar.

Adding the inputAccessoryView in textViewDidBeginEditing is probably too late. The input accessory view should be set before that, e.g., in the viewDidLoad method.
Try something like:
-(void)viewDidLoad{
[super viewDidLoad];
UIView
myTextField.inputAccessoryView = [self accessoryViewWithPreviousEnabled:NO nextEnabled:YES];
// more stuff as required...
}
And a method for creating a previous/next button (you'll need to provide your own images for the buttons and implements the previousAccessoryViewButtonTapped: and previousAccessoryViewButtonTapped: methods). It takes two BOOL parameters to indicate if the previous and/or next buttons should be enabled.
#pragma mark - Accessory view methods
-(UIView *)accessoryViewWithPreviousEnabled:(BOOL)previousEnabled nextEnabled:(BOOL)nextEnabled{
previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
previousButton.frame = CGRectMake(10, 2, 60, 30);
[previousButton setImage:[UIImage imageNamed:PREVIOUS_BUTTON] forState:UIControlStateNormal];
previousButton.enabled = previousEnabled;
[previousButton addTarget:self action:#selector(previousAccessoryViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
nextButton.frame = CGRectMake(80, 2, 60, 30);
[nextButton setImage:[UIImage imageNamed:NEXT_BUTTON] forState:UIControlStateNormal];
nextButton.enabled = nextEnabled;
[nextButton addTarget:self action:#selector(nextAccessoryViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
UIView *transparentBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 34)];
transparentBlackView.backgroundColor = [UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.6f];
UIView *accessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1024, 34)];
[accessoryView addSubview:transparentBlackView];
[accessoryView addSubview:previousButton];
[accessoryView addSubview:nextButton];
return accessoryView;
}
Note this method is hard coded for an iPad in landscape orientation. You need to change it for an iPhone.

The problem is that your self.AddView is already in your interface (because you put it there, in the storyboard). It can't be in two places at once.

Related

Button change position when alert view is showed

I am showing an alert on my UITableView.
This is the code
-(void)showAlertMaintenance{
AppDelegate * appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
[RMUniversalAlert showAlertInViewController:self withTitle:nil message:appDelegate.maintenanceStr cancelButtonTitle:#"OK" destructiveButtonTitle:nil otherButtonTitles:nil tapBlock:^(RMUniversalAlert * _Nonnull alert, NSInteger buttonIndex) {
if(buttonIndex == alert.cancelButtonIndex){
}
}];
}
The button is a subviews of one section header in my UITableview
UIButton *sendInviteCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[sendInviteCodeButton addTarget:self
action:#selector(shareInvitationCode)
forControlEvents:UIControlEventTouchUpInside];
[sendInviteCodeButton setTitle:#"招待コードをシェアする" forState:UIControlStateNormal];
[sendInviteCodeButton sizeToFit];
[sendInviteCodeButton setTitleColor:[UIColor colorWithRed:215.0f/255.0f green:116.0f/255.0f blue:52.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
sendInviteCodeButton.translatesAutoresizingMaskIntoConstraints = NO;
sendInviteCodeButton.frame = CGRectMake(20, 155.0f, SCREEN_BOUNDS_SIZE_PORTRAIT_WIDTH - 40, 30.0f);
[sendInviteCodeButton.layer setMasksToBounds:YES];
[sendInviteCodeButton.layer setCornerRadius:5.0f];
[sendInviteCodeButton.layer setBackgroundColor:[UIColor whiteColor].CGColor];
[sendInviteCodeButton setBackgroundColor:[UIColor whiteColor]];
[sendInviteCodeButton.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
[invitationView insertSubview:sendInviteCodeButton atIndex:0];
Before
After
When the alert is showed, the button is being pushed to top left corner of the screen.
Please help!
If you already calculate specific frame for your button, you should remove [sendInviteCodeButton sizeToFit];.
Just remove [sendInviteCodeButton sizeToFit];
Hope it help. :)
Since you are relying on frames to setup the layout you should have a dedicated UIView subclass for your tableview header.You need to override layoutSubviews method because at this point the header view will have it's own frame correctly set so your relative calculations for subviews (including the button) will make sense. Here's a quick sample code:
#import <UIKit/UIKit.h>
#interface MyTableViewHeader : UIView
#end
#implementation MyTableViewHeader
-(instancetype)init
{
self = [super init];
if (self) {
//setup button here (omit setting frames)
}
return self;
}
-(void)layoutSubviews
{
//set the button frame here
[super layoutSubviews];
}
#end
#interface ViewController : UIViewController<UITableViewDelegate>
#property (nonatomic, strong) MyTableViewHeader *header;
#end
#implementation ViewController
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//You will probably want some logic here
//to decide if you want to display the header
if (!self.header) {
self.header = [MyTableViewHeader new];
}
return self.header;
}
#end
As an alternative you could also setup autolayout for your table header view.
I found out the problem caused by this
[sendInviteCodeButton.layer setMasksToBounds:YES];
setMasksToBounds - is a Boolean indicating whether sublayers are clipped to the layer’s bounds

ios How to add an inputAccessoryView?

I am trying to replicate Facebook Messenger App, where there is a UITextView attached to the top of the keyboard.
Due to the nature of this app I need my view to be attached, instead of manually scrolling up and down a ScrollView when the keyboard appears.
This can be achieved by using a inputAccessoryView.
I read the docs on it here.
The documentation is very brief and says:
"This property is typically used to attach an accessory view to the system-supplied keyboard that is presented for UITextField and UITextView objects.
The value of this read-only property is nil. If you want to attach custom controls to a system-supplied input view (such as the system keyboard) or to a custom input view (one you provide in the inputView property), redeclare this property as read-write in a UIResponder subclass.
You can then use this property to manage a custom accessory view. When the receiver becomes the first responder, the responder infrastructure attaches the accessory view to the appropriate input view before displaying it."
I have tried declaring a property
#interface CommentViewController ()
#property (nonatomic, readwrite, retain) UIView *inputAccessoryView;
#end
And then setting it:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 320, 100)];
[view setBackgroundColor:[UIColor greenColor]];
self.inputAccessoryView = view;
}
Then I have tried calling both of these:
[self.tableView becomeFirstResponder];
[view becomeFirstResponder];
Nothing happens. What am I doing wrong?
*Note - Extra information: I am using a UITableViewController that I want to have a UIView attached as an inputAccessoryView. Once I get the view working then I will add in a UITextView and more, but this is mainly an example.
Any help is greatly appreciated!
Add input accessory to your textField or textView rather than to pure UIView.
self.mytextField.inputAccessoryView = view;
The inputAccessoryView is a property of the UIResponder class. It allows you to define a custom input accessory view to display when the receiver becomes the first responder. Usually an instance of UIToolBar should be set as the accessory view.
A toolbar sample:
MYInputAccessoryToolbar.h
typedef void (^MYInputAccessoryToolbarDidDoneTap)(id activeItem);
#interface MYInputAccessoryToolbar : UIToolbar
#property (nonatomic, copy) MYInputAccessoryToolbarDidDoneTap didDoneTapBlock;
+ (instancetype)toolbarWithInputItems:(NSArray *)items;
- (instancetype)initWithInputItems:(NSArray *)items;
- (void)addInputItem:(id)item;
- (void)goToNextItem;
- (void)goToPrevItem;
#end
MYInputAccessoryToolbar.m
#interface MYInputAccessoryToolbar ()
#property (strong, nonatomic) UIBarButtonItem *nextButton;
#property (strong, nonatomic) UIBarButtonItem *prevButton;
#property (strong, nonatomic) UIBarButtonItem *doneButton;
#property (nonatomic, copy) NSMutableArray *inputItems;
#property (nonatomic) NSInteger activeItemIndex;
#property (nonatomic) id activeItem;
#end
#implementation MYInputAccessoryToolbar
+ (instancetype)toolbarWithInputItems:(NSArray *)items {
return [[self alloc] initWithInputItems:items];
}
#pragma mark - Initializations
- (instancetype)init {
self = [super init];
if (self) {
_inputItems = [NSMutableArray new];
_prevButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:101 target:self action:#selector(prevButtonTaped)];
_nextButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:102 target:self action:#selector(nextButtonTaped)];
_doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleBordered target:self action:#selector(doneButtonTaped)];
[_doneButton setTitleTextAttributes:#{NSFontAttributeName:[UIFont boldSystemFontOfSize:17]} forState:UIControlStateNormal];
UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedSpace.width = 20.0f;
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray<UIBarButtonItem *> *barButtons = #[_prevButton, fixedSpace, _nextButton, flexSpace, _doneButton];
[self sizeToFit];
self.items = barButtons;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(itemDidBeginEditing:)
name:UITextFieldTextDidBeginEditingNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(itemDidBeginEditing:)
name:UITextViewTextDidBeginEditingNotification
object:nil];
}
return self;
}
- (instancetype) initWithInputItems:(NSArray *)items {
self = [self init];
for (id item in items) {
[self addInputItem:item];
}
return self;
}
#pragma mark - Accessors
- (void)addInputItem:(id)item {
if ([item respondsToSelector:#selector(setInputAccessoryView:)]) {
[item setInputAccessoryView:self];
}
[_inputItems addObject:item];
}
#pragma mark - Actions
- (void)itemDidBeginEditing:(NSNotification *)noticifation {
NSInteger itemIndex = [_inputItems indexOfObject:noticifation.object];
if (itemIndex != NSNotFound && _activeItem != noticifation.object) {
_activeItemIndex = itemIndex;
_activeItem = noticifation.object;
[self activeItemChanged];
}
}
- (void)activeItemChanged {
_prevButton.enabled = _activeItemIndex != 0;
_nextButton.enabled = _activeItemIndex != _inputItems.count - 1;
}
- (void)prevButtonTaped {
[self goToPrevItem];
}
- (void)nextButtonTaped {
[self goToNextItem];
}
- (void)goToNextItem {
[_inputItems[_activeItemIndex + 1] becomeFirstResponder];
}
- (void)goToPrevItem {
[_inputItems[_activeItemIndex - 1] becomeFirstResponder];
}
- (void)doneButtonTaped {
if (_didDoneTapBlock) {
_didDoneTapBlock(_activeItem);
}
[_activeItem resignFirstResponder];
}
#pragma mark - Dealloc
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidBeginEditingNotification object:nil];
}
#end
Now assuming that we have a set of text field fields and text views we could use them to initialize an instance of our toolbar.
MYInputAccessoryToolbar *accessoryToolbar = [MYInputAccessoryToolbar toolbarWithInputItems:#[_passwordCurrentField, _passwordNewField, _passwordVerifyField]];
And then each of these fields will have a custom accessory view like this.
Remove self.inputAccessoryView = view; and then add the code below anywhere after -(void)viewDidLoad { ... } where view is your UIView:
-(void) viewDidLoad {
....
}
- (UIView *)inputAccessoryView
{
return self.view;
}
I am posting this answer to show other people my exact code and how easy it actually was, however all the credit goes to MadNik.
In your view controller class where you want a keyboard, in the implementation add the following:
#implementation CommentViewController {
UIView *toolbar;
UITextView *commentTextView;
UIButton *postComment;
}
The toolbar is the actual view that gets docked to your keyboard, and the rest of the objects go on top of the view.
Next it is as simple as initiating the toolbar and setting its frame:
toolbar = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-50, self.view.frame.size.width, 50)];
[toolbar setBackgroundColor:[UIColor whiteColor]];
I make the frame of the toolbar initially sit right at the bottom of the view controller.
Next I just initiate the rest of the objects I want on my toolbar, e.g the UITextField and a UIButton. Just lay them out how you want:
commentTextView = [[UITextView alloc]initWithFrame:CGRectMake(8, 8, self.view.frame.size.width - 16 - 75, 34)];
[commentTextView setBackgroundColor:[UIColor colorWithWhite:0.97 alpha:1]];
commentTextView.layer.cornerRadius = 5;
[commentTextView setFont:[UIFont fontWithName:#"Avenir Next" size:20]];
[commentTextView setTextColor:[UIColor colorWithWhite:0.35 alpha:1]];
postComment = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-75, 0, 75, 50)];
[postComment setTitle:#"Post" forState:UIControlStateNormal];
[postComment.titleLabel setFont:[UIFont fontWithName:#"Avenir Next" size:20]];
[postComment setTitleColor:[UIColor colorWithRed:(255/255.0) green:(40/255.0) blue:(80/255.0) alpha:1.0] forState:UIControlStateNormal];
Next add your objects to your tool bar:
[toolbar addSubview:commentTextView];
[toolbar addSubview:postComment];
Now this is where the magic happens: You simply set your UITextView's inputAccessoryView to whatever view you want to be docked to the keyboard.
In this case it is toolbar, because the toolbar is acting as a dock that holds everything else.
Now all you need to do is add your toolbar to your view controller, and when you tap the UITextView, since its inputAccessoryView it the toolbar, the toolbar will be docked to the keyboard!
Since I am using a UITableViewController, I had to add my toolbar to the window:
[[[UIApplication sharedApplication]delegate].window addSubview:toolbar];
So simple! No extra classes or anything needs to be made!

UIView not accepting UIViewControllers data

I have a GameOver UIView that I call from inside my main UIViewController. It is just a 'popover' window that has the text game over, the score, and some blur effects to blur the main UIViewcontroller.
I try to pass an int to the UIView, but it doesn't accept it unless it is in the - (void)drawRect:(CGRect)rect method.
If I move the score label to drawRect method, the label is updated. But the blur effects go away.
What am I doing wrong?
MainViewController.m
#import "GameOverView.h"
#interface ViewController () {
GameOverView * gov;
}
- (void) showGameOver {
gov = [[GameOverView alloc] initWithFrame:self.view.bounds];
NSLog(#"Passing score of: %i", self.score);
gov.finalScore = self.score;
[self.view addSubview:gov];
}
GameOverView.h
#interface GameOverView : UIView {}
#property (nonatomic) int finalScore;
#end
GameOverView.M
#implementation GameOverView
- (id) initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//self.backgroundColor = [UIColor redColor];
NSLog(#"Score:%i", self.finalScore );
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = super.bounds;
[super addSubview:visualEffectView];
UILabel * lblGameOver = [[UILabel alloc] initWithFrame:CGRectMake(0,0, frame.size.width, 200)];
lblGameOver.center = CGPointMake(frame.size.width/2, 100);
lblGameOver.text = [NSString stringWithFormat: #"GAME OVER %i", self.finalScore];
[self addSubview:lblGameOver];
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 200)];
button.center = CGPointMake(frame.size.width/2, 200);
[button setTitle:#"Start New Game" forState:UIControlStateNormal];
[button addTarget:self action:#selector(removeSelfFromSuperview) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
- (void) removeSelfFromSuperview{
[self removeFromSuperview];
}
You are using the finalScore property in the init method of the GameOverView class, but you are only setting its value after initializing it.
Change your initialization method to
- (id) initWithFrame:(CGRect)frame finalScore:(int)fs{
// use 'fs' instead of 'self.finalScore'
}
It should work.
I wonder how there isn't any problem with the view background color. You are initializing the view and adding it as subview like this:
gov = [[GameOverView alloc] initWithFrame:self.view.bounds];
gov.finalScore = self.score;
[self.view addSubview:gov];
This will give the view background color as black which is default color. So you don't find much difference if you use blur effect.
you need to give the color for the view during the initialization :
gov = [[GameOverView alloc] initWithFrame:self.view.bounds];
[gov setBackgroundColor:[UIColor yourColor]];
[self.view addSubview:gov];
If you are planning to keep the code in initWithFrame, you don't need to worry about setting the background color. If you keep the code in drawRect, then you must set the background color,else it will be black color.
When coming to setting the score label, it doesn't matter whether you put it in drawRect or initWithFrame method. Make sure you use drawRect method only if you really have to draw on the view,so that you can call it later by using setNeedsDisplay

Adding textfield below another textfield programmatically in iOS

In my app I want to programmatically add textfield below another if required on click of a button. I already had provided two textFields. if a user want to add another textfield he can do so by clicking a button. I have already written code to obtain the textfield but the problem is that it overlaps the already designed textFields. How can I do it?
Is there any way through which I can get the x and Y co-ordinates of already designed textfield so that I can place new textField relative to those co-ordinates.
This code add textField to view dynamically when every click action on button
ExampleViewController.h
#import <UIKit/UIKit.h>
#interface ExampleViewController :UIViewController<UITextFieldDelegate>
#property int positionY;
#property int fieldCount;
#property (strong,nonatomic) UIScrollView *scroll;
#end
ExampleViewController.m
#import "ExampleViewController.h"
#interface ExampleViewController ()
#end
#implementation ExampleViewController
#synthesize positionY;
#synthesize fieldCount;
#synthesize scroll;
- (void)viewDidLoad {
[super viewDidLoad];
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.backgroundColor = [UIColor whiteColor];
[self.view addSubview:scroll];
UIButton *clickToCreateTextField = [[UIButton alloc] initWithFrame:CGRectMake(40, 80, self.view.frame.size.width-80, 75)];
[clickToCreateTextField setTitle:#"Create Text Field" forState:UIControlStateNormal];
[clickToCreateTextField addTarget:self action:#selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];
[clickToCreateTextField setBackgroundColor:[UIColor blackColor]];
[scroll addSubview:clickToCreateTextField];
positionY = clickToCreateTextField.center.y;
fieldCount = 0;
// Do any additional setup after loading the view.
}
-(void) clickedButton{
//add text field programmitacally
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(40, positionY, self.view.frame.size.width-80, 75)];
textField.delegate = self;
//give a tag to determine the which textField tapped
textField.tag = fieldCount;
textField.placeholder = [NSString stringWithFormat:#"Your dynamically created textField: %d", fieldCount ];
[scroll addSubview:textField];
//check if the textFields bigger than view size set scroll size and offset
if (positionY>= self.view.frame.size.height) {
scroll.contentOffset = CGPointMake(0, positionY);
scroll.contentSize = CGSizeMake(scroll.frame.size.width, scroll.frame.size.height+positionY);
}
fieldCount++;
//increase the position with a blank place
positionY = positionY+textField.frame.size.height+20;
}
#pragma mark TextField Delegate Methods
-(void) textFieldDidBeginEditing:(UITextField *)textField{
//Do what ever you want
}
-(void) textFieldDidEndEditing:(UITextField *)textField{
[textField resignFirstResponder];
//do anything
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
You can do any additional changes on this code.
I think this example explain your answer.
Hope it helps.
Use a counter and calculate y like this counter*texfield.frame.size.height.

Sliding the keyboard to the left in iOS

I'm wondering if there is a way to slide the first-responder keyboard to the left or to the right when the user press a button.
http://cl.ly/image/143K3t403d1m/1.png
I make the button as a keyboard-accessory view. When it's tapped the keyboard should slide to the left displaying another custom inputs panel.
Any ideas?
If you want a keyboard that can be selected from the system (using the globe key), you'll need to read this article about creating a Custom Keyboard App Extension for iOS 8.
If you just want to be able to switch between inputView objects, the following code will get you there:
// ViewController.m
#import "ViewController.h"
#interface ViewController () {
}
#pragma mark -
#pragma mark - UI Controls
#property (strong, nonatomic) UIInputView *inputView;
#property (strong, nonatomic) UITextField *textField;
#end
#implementation ViewController
#pragma mark -
#pragma mark - View Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUserInterface];
}
#pragma mark -
#pragma mark - Keyboard switching
- (void)switchKeyboard {
// Simply toggle the "inputView" for self.textField
if (self.textField.inputView == nil) {
self.textField.inputView = self.inputView;
} else {
self.textField.inputView = nil;
}
[self.textField resignFirstResponder];
[self.textField becomeFirstResponder];
}
#pragma mark -
#pragma mark - UI Setup
// All of the code below here
// is for pure, in-code AutoLayout
- (void)setupUserInterface {
[self createControls];
[self setupControls];
[self layoutControls];
}
- (void)createControls {
self.textField = [[UITextField alloc] init];
self.textField.borderStyle = UITextBorderStyleRoundedRect;
self.inputView = [[UIInputView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 216.0f)];
self.inputView.backgroundColor = [UIColor lightGrayColor];
}
- (void)setupControls {
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44.0f)];
toolbar.backgroundColor = [UIColor lightGrayColor];
// When the button is tapped, it'll execute "switchKeyboard" above
UIBarButtonItem *switchButton = [[UIBarButtonItem alloc] initWithTitle:#"Switch" style:UIBarButtonItemStyleDone target:self action:#selector(switchKeyboard)];
toolbar.items = #[switchButton];
self.textField.inputAccessoryView = toolbar;
[self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
}
- (void)layoutControls {
[self.view addSubview:self.textField];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-[textfield]-|"
options:0
metrics:nil
views:#{#"textfield": self.textField}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-(height)-[textfield(==height)]"
options:0
metrics:#{#"height" : #(40)}
views:#{#"textfield": self.textField}]];
}
#end
Caveat: You will need to do a lot of tweaking to make sure the user experience is good. In my testing, on the simulator (iPhone 4S), this works ok, but isn't the smoothest user experience.

Resources