I am new to iOS i need to display objectAtIndex(0) in textfield using uipickerview .while run the app textfield empty after selection in picker view only value can displayed in textfield i need initially textfield not be empty.
viewdidload code:
pktStatePicker .delegate = self;
pktStatePicker .dataSource = self;
[ pktStatePicker setShowsSelectionIndicator:YES];
txtText.inputView = pktStatePicker ;
// Create done button in UIPickerView
UIToolbar* mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClicked)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
txtText.inputAccessoryView = mypickerToolbar;
picker view delegates:
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog([arrmsg1 objectAtIndex:row]);
txtText.text = (NSString *)[arrMsg objectAtIndex:row];
}
set like on your ViewDidLoad, but ensure once your arrMsg.count!=0
- (void)viewDidLoad
{
[super viewDidLoad];
txtText.text = (NSString *)[arrMsg objectAtIndex:0];
}
choice-2
or when you append the data in arrMsg after that call like
if (arrMsg.count >0)
{
txtText.text = (NSString *)[arrMsg objectAtIndex:0];
}
there after continue your work asuseual
I have an app with four viewControllers, and there is a lot of code that is repeating exactly the same way in the four view controllers, and I would like to know what is the best OOP way to write this code only one time and reuse it in the others view controllers.
This is the code from viewDidLoad of my first view controller:
- (void)viewDidLoad {
[super viewDidLoad];
[self setCanDisplayBannerAds:YES];
[[[self.tabBarController.viewControllers objectAtIndex:1] tabBarItem]setImage:[UIImage imageNamed:#"iconoBota30x30.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:2] tabBarItem]setImage:[UIImage imageNamed:#"actividades.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:3] tabBarItem]setImage:[UIImage imageNamed:#"nosotros.png"]];
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
static_iVar = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
static_iVar.delegate = self;
NSURL *url = [NSURL URLWithString:#"http://guiasdelsur.es"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar loadRequest:requestObj];
[self.view addSubview:static_iVar];
//GESTURES
//DOWN
UISwipeGestureRecognizer *gest1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(hideTabBar:)];
gest1.delegate = self;
[gest1 setDirection:UISwipeGestureRecognizerDirectionDown];
[self.view addGestureRecognizer:gest1];
//UP
UISwipeGestureRecognizer *gest2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(showTabBar:)];
gest2.delegate = self;
[gest2 setDirection:UISwipeGestureRecognizerDirectionUp];
[self.view addGestureRecognizer:gest2];
//first tab
_tabInicio = [[UITabBarItem alloc] initWithTitle:#"Inicio" image:[UIImage imageNamed:#"d.png"] tag:0];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:0];
self.tabBarItem = _tabInicio;
_cToolBar = [[UIToolbar alloc] init];
_cToolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
[_cToolBar setBarStyle:UIBarStyleBlack];
[_cToolBar setTranslucent:YES ];
[_cToolBar setTintColor:[UIColor greenColor]];
// Do any additional setup after loading the view, typically from a nib.
NSString *backArrowString = #"\U000025C0\U0000FE0E AtrĂ¡s"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR
UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStyleDone target:nil action:#selector(goBack)];
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:nil action:#selector(refreshControl)];
[right setTintColor:[UIColor greenColor]];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[items addObject:back];
[items addObject:flexibleSpace];
[items addObject:right];
[_cToolBar setItems:items animated:NO];
[self.view addSubview:_cToolBar];
//iAD
ADBannerView * adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, 44);
adView.delegate = self;
[self.view addSubview:adView];
//loading indicator
_indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[_indicator setCenter:self.view.center];
[_indicator setHidesWhenStopped:YES];
[self.view addSubview:_indicator];
[_indicator startAnimating];
}
And this is the code from viewDidLoad method of my secondViewController, very similar to the first one. The differences in all my view controllers are the same than those ones.
- (void)viewDidLoad {
[super viewDidLoad];
[self setCanDisplayBannerAds:YES];
float width = [UIScreen mainScreen].bounds.size.width;
float height = [UIScreen mainScreen].bounds.size.height;
static_iVar2 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, width,height)];
static_iVar2.delegate = self;
NSURL *url = [NSURL URLWithString:#"http://guiasdelsur.es/category/programas/"];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[static_iVar2 loadRequest:requestObj];
[self.view addSubview:static_iVar2];
//second tab
_secondTab = [[UITabBarItem alloc] initWithTitle:#"Programas" image:[UIImage imageNamed:#"iconoBota30x30.png"] tag:1];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];
[self.tabBarController setSelectedIndex:1];
self.tabBarItem = _secondTab;
//GESTURES
//DOWN
UISwipeGestureRecognizer *gest1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(hideTabBar:)];
gest1.delegate = self;
[gest1 setDirection:UISwipeGestureRecognizerDirectionDown];
[self.view addGestureRecognizer:gest1];
//UP
UISwipeGestureRecognizer *gest2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(showTabBar:)];
gest2.delegate = self;
[gest2 setDirection:UISwipeGestureRecognizerDirectionUp];
[self.view addGestureRecognizer:gest2];
UIToolbar *cToolBar = [[UIToolbar alloc] init];
cToolBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44);
NSMutableArray *items = [[NSMutableArray alloc] init];
[cToolBar setBarStyle:UIBarStyleBlack];
[cToolBar setTranslucent:YES ];
[cToolBar setTintColor:[UIColor greenColor]];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil ];
UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:nil action:#selector(refreshControl)];
[right setTintColor:[UIColor greenColor]];
[items addObject:flexibleSpace];
[items addObject:right];
[cToolBar setItems:items animated:NO];
[self.view addSubview:cToolBar];
//iAD
ADBannerView * adView = [[ADBannerView alloc] initWithFrame:CGRectZero];
adView.frame = CGRectOffset(adView.frame, 0, 44);
adView.delegate = self;
[self.view addSubview:adView];
//Indicator
_indicador = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[_indicador setCenter:self.view.center];
[_indicador setHidesWhenStopped:YES];
[self.view addSubview:_indicador];
[_indicador startAnimating];
}
It is a very good idea to refactor this code; it is an example of DRY. The best way in this case would be to use inheritance: write all common code in the ViewController class, e.g.
ViewController.h
#interface ViewController : UIViewController {
// Variables which are declared here can also be used in the subclasses
}
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[self setCanDisplayBannerAds:YES];
// more common code
...
}
and have your other view controllers inherit from ViewController (rather than UIViewController):
FirstViewController.h
#interface FirstViewController : ViewController
...
FirstViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// more specific code
[[[self.tabBarController.viewControllers objectAtIndex:1] tabBarItem]setImage:[UIImage imageNamed:#"iconoBota30x30.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:2] tabBarItem]setImage:[UIImage imageNamed:#"actividades.png"]];
[[[self.tabBarController.viewControllers objectAtIndex:3] tabBarItem]setImage:[UIImage imageNamed:#"nosotros.png"]];
...
}
I have a weird bug which only happens in iPhone 6 simulator in Xcode 6. I have a generic component which extends UITextField and shows a pickerView as inputView at the bottom of screen.
If I use iPhone5 or iPhone5s to test my application, it's working as expected: inputView and inputAccessoryView is displaying correctly. But if I switch to iPhone 6 or Plus simulator, only inputAccessoryView is shown at bottom of screen, inputView is not showing.
Here is my code:
#interface DropDownTextField : UITextField
#property (strong,nonatomic) UIPickerView* pickerView;
#property (strong,nonatomic) UIToolbar *toolBar;
#property CGFloat originalFontSize;
#property (nonatomic) id<UIPickerViewDelegate> pickerDelegate;
#property (nonatomic) id<UIPickerViewDataSource> pickerDataSource;
- (CGFloat)requiredFontSize;
- (void)setDropdownMode:(BOOL)enabled;
#end
#implementation DropDownTextField
-(id)initWithCoder:(NSCoder *)aDecoder {
if(self = [super initWithCoder:aDecoder]) {
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
[self setFont:[UIFont mediumRegular]];
_originalFontSize = self.font.pointSize;
self.layer.borderWidth = 1.0f;
CGRect frame = [self frame];
// rightview dropdown arrow
UIImageView *dropDownImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, (frame.size.height-8)/2, 14.0f, 8.0f)];
UIImage *dropDownImage = [UIImage imageNamed:#"DisclosureDown"];
[dropDownImageView setImage:dropDownImage];
dropDownImageView.contentMode = UIViewContentModeScaleAspectFit;
UIView *dropDownView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25.0f, frame.size.height)];
[dropDownView addSubview:dropDownImageView];
self.rightView = dropDownView;
self.rightViewMode = UITextFieldViewModeAlways;
[self.rightView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(becomeFirstResponder)]];
// picker view
_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,216)];
_pickerView.showsSelectionIndicator = YES;
[_pickerView setBackgroundColor:[UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f]];
self.inputView = _pickerView;
// picker view toolbar
_toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,44)];
[_toolBar setBackgroundColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[_toolBar setBarStyle:UIBarStyleBlackTranslucent];
// to align button to the right
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] init];
[barButtonDone setTarget:self];
[barButtonDone setAction:#selector(changeSelectionFromLabel:)];
[barButtonDone setTitle:NSLocalizedString(#"ok", #"")];
[barButtonDone setTintColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[barButtonDone setStyle:UIBarButtonItemStylePlain];
[barButtonDone setTitleTextAttributes:[UIFont pickerTitleTextAttributes] forState:UIControlStateNormal];
UIBarButtonItem *barButtonCancel = [[UIBarButtonItem alloc] init];
[barButtonCancel setTarget:self];
[barButtonCancel setAction:#selector(dismissPickerView:)];
[barButtonCancel setTitle:NSLocalizedString(#"cancel", #"")];
[barButtonCancel setTintColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1.0f]];
[barButtonCancel setStyle:UIBarButtonItemStylePlain];
[barButtonCancel setTitleTextAttributes:[UIFont pickerTitleTextAttributes] forState:UIControlStateNormal];
self.toolBar.items = [[NSArray alloc] initWithObjects:barButtonCancel,flex,barButtonDone,nil];
self.inputAccessoryView = _toolBar;
}
return self;
}
Does anybody come across such a problem? Any ideas to resolve?
PS: I've already tried clearing build directory, clean/rebuild project, stop/restart simulator and xcode approaches. Not working.
try to uncheck simulator -> hardware -> keyboard - > connect hardware keyboard
I have written the following code in the viewDidLoad method:
categoryPickerView=[[UIPickerView alloc]init];
categoryPickerView.alpha = 0;
[self.view addSubview:categoryPickerView];
categoryPickerView.delegate=self;
categoryPickerView.tag=1;
and called this method to hide picker view
- (IBAction)hidePickerView:(id)sender {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.6];
CGAffineTransform transfrom = CGAffineTransformMakeTranslation(0, 200);
categoryPickerView.transform = transfrom;
categoryPickerView.alpha = categoryPickerView.alpha * (-1) + 1;
[UIView commitAnimations];
}
My problem is that I want to display a "Done" button on a picker view and the picker view should hide on button click.
You can use this code,
UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleBordered target:self action:#selector(changeDateFromLabel:)];
toolBar.items = #[barButtonDone];
barButtonDone.tintColor=[UIColor blackColor];
[pickerView addSubview:toolBar];
//(or)pickerView.inputAccessoryView = toolBar;
and set button action method for changeDateFromLabel:
-(void)changeDateFromLabel:(id)sender
{
[[your UI Element] resignFirstResponder];
}
You can create view and add toolbar with "Done" button and UIPickerView as subviews
- (void)createInputView {
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
[toolBar setBarStyle:UIBarStyleDefault];
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:#"Done"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(doneClicked)];
toolBar.items = #[flex, barButtonDone];
barButtonDone.tintColor = [UIColor blackColor];
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, toolBar.frame.size.height, screenWidth, 200)];
picker.delegate = self;
picker.dataSource = self;
picker.showsSelectionIndicator = YES;
UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, toolBar.frame.size.height + picker.frame.size.height)];
inputView.backgroundColor = [UIColor clearColor];
[inputView addSubview:picker];
[inputView addSubview:toolBar];
textField.inputView = inputView;
}
- (void)doneClicked {
[textField resignFirstResponder];
}
You need to use the UIToolbar as the accessory view:
Try with this:
#pragma mark - PickerView for Location Selection
- (UIPickerView *)locationsPicker {
if ( locationsPicker == nil ) {
locationsPicker = [[UIPickerView alloc] init];
locationsPicker.delegate = self;
locationsPicker.dataSource = self;
locationsPicker.showsSelectionIndicator = YES;
}
return locationsPicker;
}
- (UIToolbar *)accessoryView {
if ( accessoryView == nil ) {
accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
UIBarButtonSystemItemDone
target:self
action:#selector(onLocationSelection)];
[accessoryView setItems:[NSArray arrayWithObject:doneButton]];
}
return accessoryView;
}
- (void)onLocationSelection {
NSInteger row = [self.locationsPicker selectedRowInComponent:0];
if ( [Location isFirstResponder] ) {
NSLog(#"%#", [listOfLocations objectAtIndex:row]);
[Location resignFirstResponder];
}
}
Copy-pasteable solution!
This works in iOS 10 (and probably other versions too) I wrote this code on 9/4/2017.
I needed to combine other answers to get what I wanted, which was a Cancel button, Done button, and a picker view that would show/hide on the tap of a button. Ignore the fact that my screenshot only has one item in the picker.. I only have one item in my array. I've tested multiple items, it works fine.
Disclaimer! I have tested and used this code. I generalized the names in my example, so I apologize in advance if I missed one and they property names don't line up.
In order to have a pickerView that appears on the tap of a button, you need to create a dummyTextField (of type UITextField anywhere in your view controller. This is because UIPickerView's are designed to work with UITextFields. To mimic showing and hiding of the picker, your button taps need to call the dummyTextField's becomeFirstResponder and resignFirstResponder methods. (examples are below)
Step one
Create a custom data source class. MyObj is the class you want to have items show up in the picker for.
In .h:
#import <UIKit/UIKit.h>
#class myObj;
#interface PickerDataSource : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>
#property (nonatomic, strong) MyObj *selectedObject;
#end
In .m:
#import "PickerDataSource.h"
#import "MyObj.h"
#implementation PickerDataSource
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
self.selectedObject = mySourceArray[row];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return mySourceArray.count;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return ((MyObj *)mySourceArray[row]).myTitle;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
int sectionWidth = 300;
return sectionWidth;
}
#end
Step two In your view controller, import custom data source, delegate, and set properties: (You must include the text field delegate!)
#import "PickerDataSource.h"
#interface MyViewController () <UIPickerViewDelegate, UITextFieldDelegate>
#property (strong, nonatomic) PickerDataSource *pickerDataSource;
#property (strong, nonatomic) UIPickerView *picker;
#property (strong, nonatomic) UITextField *dummyTextField;
#end
Step three
In your viewDidLoad, call [self setupPicker]; (you'll create this method next)
Step four
Create setupPicker
- (void)setupPicker {
// init custom picker data source
self.pickerDataSource = [PickerDataSource new];
// init custom picker
self.picker = [UIPickerView new];
// set the picker's dataSource and delegate to be your custom data source
self.picker.dataSource = self.pickerDataSource;
self.picker.delegate = self.pickerDataSource;
self.picker.showsSelectionIndicator = YES;
// next step is to write this configure method getting called here
[self configurePickerSubviews];
// lastly, add the dummyTextField to your view.
[self.view addSubview:self.dummyTextField];
}
Step five
Create configurePickerSubviews
- (void)configurePickerSubviews {
// A UIPickerView must be added as an inputView to a UITextField in order to be displayed on button tap
// So you need to create a dummyTextField to do so.
self.dummyTextField = [UITextField new];
// Create a toolbar to add a done button
UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width,44)];
[toolBar setBarStyle:UIBarStyleDefault];
UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStylePlain target:self action:#selector(locationPressed)];
// Create a flex space so that done button will be right aligned
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(dismissPicker)];
toolBar.items = #[cancel, flex, done];
done.tintColor = [UIColor blackColor];
[self.picker addSubview:toolBar];
// Create an input view to add picker + done button as subviews
UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.picker.frame.size.height + 44)];
[self.picker setFrame:CGRectMake(0, 0, inputView.frame.size.width, inputView.frame.size.height)];
inputView.backgroundColor = [UIColor clearColor];
[inputView addSubview:self.picker];
[inputView addSubview:toolBar];
// Set custom inputView as container for picker view
self.dummyTextField.inputView = inputView;
// Hiding the textfield will hide the picker
[self.dummyTextField setHidden:YES];
}
Step six
Configure the PickerDataSource so that it is fetching the data you want to display from your source array.
Step 7
Click Run!
The UIToolbar with the 'Done' button should be added to the inputAccessoryView of the view that becomes first responder. As the UIView class inherits from UIResponder, any view can potentially contain an inputView and inputAccessoryView. So instead of manually performing the animations programmatically, you could use the default animation behaviour that comes with the UIResponder's keyboard show/hide animation.
Subclass a UIView and override the inputView and inputAccessoryView properties and make them readwrite. In this example, I will subclass a UITableViewCell.
// FirstResponderTableViewCell.h
#interface FirstResponderTableViewCell : UITableViewCell
#property (readwrite, strong, nonatomic) UIView *inputView;
#property (readwrite, strong, nonatomic) UIView *inputAccessoryView;
#end
Override canBecomeFirstResponder in your subclass' implementation.
// FirstResponderTableViewCell.m
- (BOOL)canBecomeFirstResponder {
return YES;
}
In your view controller, create and assign the picker view and input accessory toolbar
// MyViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
UIPickerView *pickerView = [[UIPickerView alloc] init];
UIToolbar *accessoryToolbar = [UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
// Configure toolbar .....
// note: myFirstResponderTableViewCell is an IBOutlet to a static cell in storyboard of type FirstResponderTableViewCell
self.myFirstResponderTableViewCell.inputView = pickerView;
self.myFirstResponderTableViewCell.inputAccessoryView = accessoryToolbar;
}
Don't forget to assign first responder to the view when required (e.g. inside - tableView:didSelectRowAtIndexPath:)
[self.myFirstResponderTableViewCell becomeFirstResponder];
Hope this helps.
Reference: http://blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/
Try this.
UIPickerView *cityPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
cityPicker.delegate = self;
cityPicker.dataSource = self;
[cityPicker setShowsSelectionIndicator:YES];
txtText.inputView = cityPicker;
// Create done button in UIPickerView
UIToolbar* mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClicked)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
txtText.inputAccessoryView = mypickerToolbar; // set the toolbar as input accessory view for uitextfield, not the pickerview.
http://technopote.com/how-to-make-multiple-uipickerview-in-a-single-view/
#import "ViewController.h"
#interface ViewController ()<UIPickerViewDelegate>
{
UIPickerView *myPickerView;
NSArray *namesArray ;
}
#end
#implementation ViewController
-(void)viewDidLoad
{
[super viewDidLoad];
namesArray=[[NSArray alloc]initWithObjects:#"a",#"b", nil];
[self popoverWithInformation];
}
-(void)popoverWithInformation
{
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:#selector(pickerCancel:)];
[barItems addObject:cancelBtn];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDone:)];
[barItems addObject:doneBtn];
[pickerToolbar setItems:barItems animated:YES];
myPickerView = [[UIPickerView alloc] init];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
CGRect pickerRect = myPickerView.bounds;
myPickerView.bounds = pickerRect;
myPickerView.frame = CGRectMake(0, 44, 320, 216);
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 300)];
popoverView.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:myPickerView];
[popoverView addSubview:pickerToolbar];
[self.view addSubview:popoverView];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {
}
// tell the picker how many rows are available for a given component
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return namesArray.count;
}
// tell the picker how many components it will have
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
// tell the picker the title for a given component
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return namesArray[row];
}
// tell the picker the width of each row for a given component
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
int sectionWidth = 300;
return sectionWidth;
}
-(void)pickerDone:(id)sender
{
}
-(void)pickerCancel:(id)sender
{
}
In Swift 5 try this,
func setToolBar() {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44))
toolBar.barStyle = UIBarStyle.default
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.donePicker))
toolBar.setItems([doneButton],animated: false)
toolBar.isUserInteractionEnabled = true
doneButton.tintColor = UIColor.black
picker.addSubview(toolBar)
}
#objc func donePicker() {
// hide keypad
}
In my iPad app, i add navigation bar and tool bar manually.
I also add scroll view and image view by coding.
My problem is i can see both navigation bar and tool bar.
I can click button on navigation bar.
But, i can't click bar button on tool bar.
How can i do it?
This is my code.
- (void)viewDidLoad
{
[super loadView];
self.view.backgroundColor = [UIColor grayColor];
UIScrollView *ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height)];
ScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
// Create a UIImage to hold Info.png
UIImage *image1 = [UIImage imageNamed:#"Image-001.jpg"];
UIImage *image2 = [UIImage imageNamed:#"Image-002.jpg"];
UIImage *image3 = [UIImage imageNamed:#"Image-003.jpg"];
UIImage *image4 = [UIImage imageNamed:#"Image-004.jpg"];
NSArray *images = [[NSArray alloc] initWithObjects:image1,image2,image3,image4,nil];
UIImageView *ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height-88)];
[ImageView setImage:[images objectAtIndex:i]];
[ScrollView addSubview:ImageView];
}
ScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:ScrollView];
}
I dont Know what is your exact problem, Because your displayed code is not related to UIToolBar.
But Following code i added two UIBarButton with flexSpace.
you can add UIBarButton as you want
UIToolbar *Toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
Toolbar = UIBarStyleBlackTranslucent;
[Toolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
[flexSpace release];
UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStyleBordered target:self action:#selector(Cancel)];
[barItems addObject:btnCancel];
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleBordered target:self action:#selector(done)];
[barItems addObject:btnDone];
[Toolbar setItems:barItems animated:YES];
Following Method is call when tapped on bar Button
-(void)Cancel
{
// Write Code for Cancel Method
}
-(void)done
{
// Write Code for Done Method
}
This code might helpful in your own case.
Thanks :)
Thanks everybody. I can solve my problem.
I change my code.
UIScrollView *ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height)];
To this.
UIScrollView *ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-88)];