Why isn't my IBAction firing? - ios

I have a custom class (FFFuelQuantityPickerVC) Storyboard View Controller that contains a UIPickerView and a UIButton. The UIButton is wired to an IBAction called fullButtonPressed in FFFuelQuantityPickerVC. When this View Controller is presented using a storyboard popover segue, the fullButtonPressed IBAction is fired when the UIButton is "touched up inside."
However, when I programmatically init and present FFFuelQuantityPickerVC in a popup, pressing the UIButton does not fire the IBAction. Why would that be? Here is the code that does the programmatic presentation when a button in a UITableViewCell is pressed. (self.poc is a reusable popover controller):
-(void)thisHelperPressed:(UIButton *)thisHelper inCell:(UITableViewCell *)thisCell{
if ([thisHelper.titleLabel.text isEqualToString:#"FuelPicker"]){
//init the fuel quantity picker VC
FFFuelQuantityPickerVC *fuelQuantityPickerVC;
fuelQuantityPickerVC =[[UIStoryboard storyboardWithName:#"MainStoryboard"
bundle:nil]
instantiateViewControllerWithIdentifier:#"FuelQuantityPickerVC"];
fuelQuantityPickerVC.delegate = self;
[self.poc setContentViewController:fuelQuantityPickerVC];
} else if...
}
self.poc.delegate = self;
//present it
[self.poc presentPopoverFromRect:thisHelper.frame inView:thisCell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
.
.
.
Here is FFFuelQuantityPickerVC:
// FFFuelQuantityPickerVC.h
#import <UIKit/UIKit.h>
#protocol fuelPickerDelegate <NSObject>
-(void) fuelQuantityChangedL:(NSInteger) quantityL R:(NSInteger)quantityR;
#end
#interface FFFuelQuantityPickerVC : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
#property (weak, nonatomic) IBOutlet UIPickerView *thisPicker;
#property (nonatomic) NSString *fuelQuantityL;
#property (nonatomic) NSString *fuelQuantityR;
#property (nonatomic) id delegate;
- (IBAction)fullButtonPressed; //this is wired to the button
#end
//
// FFFuelQuantityPickerVC.m
#import "FFFuelQuantityPickerVC.h"
#define FUEL_MIN 0
#define FUEL_MAX 146
#define LEFT_COMPONENT 0
#define RIGHT_COMPONENT 1
#interface FFFuelQuantityPickerVC ()
#end
#implementation FFFuelQuantityPickerVC
- (void)viewDidLoad
{
[super viewDidLoad];
if (!self.fuelQuantityL){
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX];
}
if (!self.fuelQuantityR){
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX];
}
}
//set selected row to current values, if any
- (void) viewDidAppear:(BOOL)animated {
[self.thisPicker selectRow:FUEL_MAX - [self.fuelQuantityL intValue] inComponent:LEFT_COMPONENT animated:YES];
[self.thisPicker selectRow:FUEL_MAX - [self.fuelQuantityR intValue] inComponent:RIGHT_COMPONENT animated:YES];
}
//this method does not get called when the button is pressed (except when the VC is presented via storyboard popover segue)
- (IBAction)fullButtonPressed {
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX];
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX];
[self.thisPicker selectRow:0 inComponent:0 animated:YES];
[self.thisPicker selectRow:0 inComponent:1 animated:YES];
[self.delegate fuelQuantityChangedL:[self.fuelQuantityL integerValue]
R:[self.fuelQuantityR integerValue]];
}
#pragma mark - PickerViewDataSource delegate methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return (FUEL_MAX-FUEL_MIN + 1);
}
#pragma mark - PickerView delegate methods
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
float myWidth = self.view.frame.size.width;
if (component == 0) return myWidth / 3;
return (myWidth * 2 / 3);
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
//TODO
return 28;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [NSString stringWithFormat:#"%d", (FUEL_MAX)-row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if (component == LEFT_COMPONENT){
self.fuelQuantityL = [NSString stringWithFormat:#"%i", FUEL_MAX - row];
} else {
self.fuelQuantityR = [NSString stringWithFormat:#"%i", FUEL_MAX - row];
}
[self.delegate fuelQuantityChangedL:[self.fuelQuantityL integerValue]
R:[self.fuelQuantityR integerValue]];
}
#end

Here is my code. I m using this code for display the UIPopoverController when I click the cell and pick the value from UIPickerView to display the value in UILabel in my UITableviewCell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
if (indexPath.row == 1)
{
//PopoverView controller.........................................................................
UIViewController *popoverViewController = [[UIViewController alloc] init];
//PopoverView....................................................................................
UIView *popoverView = [[UIView alloc]init];
[popoverView setBackgroundColor:[UIColor blackColor]];
//Navigation bar and Barbutton items..............................................................
UINavigationBar *navBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
navBar.barStyle = UIBarStyleBlackTranslucent;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doDone)];
UIBarButtonItem *btnCancel = [[UIBarButtonItem alloc]initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(doCancel)];
UINavigationItem *navItem = [[UINavigationItem alloc]init];
navItem.rightBarButtonItem = btnDone;
navItem.leftBarButtonItem = btnCancel;
navBar.items = [[NSArray alloc]initWithObjects:navItem, nil];
[popoverView addSubview:navBar];
//UIPickerView.....................................................................................
UIPickerView *sortPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 50, 320, 180)];
popoverViewController.contentSizeForViewInPopover = CGSizeMake(320, 230);
sortPickerView.delegate = self;
sortPickerView.dataSource = self;
sortPickerView.showsSelectionIndicator = YES;
[popoverView addSubview:sortPickerView];
NSUserDefaults *ud1 = [NSUserDefaults standardUserDefaults];
if ([ud1 objectForKey:#"languages"])
{
NSUInteger row1 = [languages indexOfObject:[ud1 objectForKey:#"languages"]];
if (row1)
{
[sortPickerView selectRow:row1 inComponent:0 animated:YES];
}
}
else
{
[sortPickerView selectRow:0 inComponent:0 animated:YES];
}
CGRect popFrame = lbl_language.frame;
popFrame.origin.y = popFrame.origin.y + popFrame.size.height + 70;
popFrame.origin.x = popFrame.origin.x + 100;
popoverViewController.view = popoverView;
self.SortPopover = [[UIPopoverController alloc] initWithContentViewController:popoverViewController];
[self.SortPopover presentPopoverFromRect:popFrame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
}

For reasons that are unclear to me, the UI Button was not receiving the push - it never highlighted. It was not overlaid by another view that I could see (the only other view was the picker). Anyway, I added a UIToolbar and changed the button to a bar button item and it works fine.

Related

PickerView is not dismissing when Done button is pressed

I have created a text field that upon entry will open a picker view with a toolbar that contains a done button. However, when the done button is pressed the picker view doesn't dismiss. Everything else works just as I want except this. I've tried several options to no avail. Please review and let me know what I'm missing.
My code is below:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{IBOutlet UITextField *productDescription; IBOutlet UIPickerView *productPicker; NSArray *productListArray}
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)addPickerView{
productListArray = [[NSArray alloc]initWithObjects:
#"myArray", nil];
productDescription.delegate = self;
[self.view addSubview:productDescription];
[productDescription setPlaceholder:#"Product Description"];
productPicker = [[UIPickerView alloc]init];
productPicker.dataSource = self;
productPicker.delegate = self;
productPicker.showsSelectionIndicator = YES;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
initWithTitle:#"Done" style:UIBarButtonItemStyleDone
target:self action:#selector(resignFirstResponder)];
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:
CGRectMake(50, 320, 50, 50)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
NSArray *toolbarItems = [NSArray arrayWithObjects:
doneButton, nil];
[toolBar setItems:toolbarItems];
productDescription.inputView = productPicker;
productDescription.inputAccessoryView = toolBar;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self addPickerView];
}
#pragma mark - Text field delegates
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
([textField.text isEqualToString:#""]);
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
return [productListArray count];
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
[productDescription setText:[productListArray objectAtIndex:row]];
}
- (void)doneButton:(UIBarButtonItem *)sender{
NSLog(#"Done Touched");
[productPicker setHidden:YES];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component{
return [productListArray objectAtIndex:row];
}
#end
.M File
Xib file in take Textfield and set delegate with connect.
#import "YourViewController.h"
#interface YourViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
UIPickerView *productPicker;
NSArray *productListArray;
IBOutlet UITextField *productDescription;
}
#end
- (void)viewDidLoad
{
[super viewDidLoad];
[self addPickerView];
}
-(void)addPickerView
{
productListArray = [[NSArray alloc]initWithObjects:#"myArray",#"Rohit",#"Change",#"Your view", nil];
[productDescription setPlaceholder:#"Product Description"];
productPicker = [[UIPickerView alloc]init];
productPicker.dataSource = self;
productPicker.delegate = self;
productPicker.showsSelectionIndicator = YES;
UIToolbar* toolBar = [[UIToolbar alloc] init];
toolBar.barStyle = UIBarStyleBlack;
toolBar.translucent = YES;
toolBar.tintColor = nil;
[toolBar sizeToFit];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(doneButton:)];
[toolBar setItems:[NSArray arrayWithObjects:doneButton, nil]];
productDescription.inputView = productPicker;
productDescription.inputAccessoryView = toolBar;
}
- (IBAction)doneButton:(id)sender
{
NSLog(#"Done Touched");
[productPicker removeFromSuperview];
[productPicker resignFirstResponder];
[self.view endEditing:YES];
}
#pragma mark - Text field delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField {
productDescription.inputView = productPicker;
}
#pragma mark - Text field delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField {
productDescription.inputView = productPicker;
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [productListArray count];
}
#pragma mark- Picker View Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
[productDescription setText:[productListArray objectAtIndex:row]];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [productListArray objectAtIndex:row];
}
I hope this will help you great.

UIPickerView select row doesn't work ios7

I have a UIPickerView that is being "pushed" to UINavigationController like this:
[self.navigationController pushViewController:vc animated:YES];
I would like to set the selected row.
I added in ViewDidAppear:
for (int i = 0; i < [countryCodes count]; i++)
{
if ([[countryCodes objectAtIndex:i] isEqualToString:selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
where i is dynamic (being changed based on data that is changing in that view controller)
It works only if I restart the app.
If I go back and forth in the navigation it doesn't work
How can I make the UIPickerView choose the the correct row?
I can see in debug mode that the lines in viewDidAppear are called. Maybe the component is being created and I can't change it?
This is how I create the UIPickerView:
- (void)viewDidLoad
{
_countryPicker = [[UIPickerView alloc] init];
[self initPicker:_countryPicker textField:_countryText];
}
- (void)initPicker:(UIPickerView*)pickerView textField:(UITextField*) textField
{
CGRect pickerFrame = CGRectMake(0, 0, 200, 216);
pickerView.frame = pickerFrame;
pickerView.userInteractionEnabled = YES;
pickerView.dataSource = self;
pickerView.hidden = YES;
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
[textField setInputView:pickerView];
textField.delegate = self;
[pickerView removeFromSuperview];
}
You wrote: "where i is dynamic (being changed based on data that is changing in that view controller)""
In your code i is a local variable. Did you mean selectedCountryCode here?
for (int i = 0; i < [countryCodes count]; i++)
{
if ([[countryCodes objectAtIndex:i] isEqualToString:selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
I am pretty sure selectedCountryCode is not updated correctly. Add NSLog(selectedCountryCode); to check it.
UPDATE:
It seems that problem is somewhere inside a code you did not post in the question. To check your code I created and share a project. Please find it here https://github.com/Avtolic/SOHelper If you will check it you will find that everything works ok.
After you set the selected row you then call this...
[_countryPicker reloadAllComponents];
Thats going to wipe out your selection? I would remove that line
If you make the selectedCountryCode variable part of a singleton class (for example AppDelegate or preferebly some other), and then equate the value, this is surely going to work. Here I don't understand how the selectedCountryCode is expected to be retained even after the view is popped.
I tried with making the string a part of AppDelegate (which is of course not a good practice. One should put it in another singleton class).
#import "CViewController.h"
#import "AppDelegate.h"
#interface CViewController ()<UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource>
#property(nonatomic, strong) UIPickerView *countryPicker;
#property (nonatomic, weak) IBOutlet UITextField *countryText;
#property (nonatomic, strong) NSArray *countryCodes;
#property (nonatomic, assign) int countrySelectedRow;
#property (nonatomic,strong) AppDelegate *delegate;
#end
#implementation CViewController
- (void)viewDidLoad
{
self.delegate = [[UIApplication sharedApplication] delegate];
_countryPicker = [[UIPickerView alloc] init];
[self initPicker:_countryPicker textField:_countryText];
self.countryCodes = #[#"A", #"B", #"C", #"D", #"E"];
}
- (void)initPicker:(UIPickerView*)pickerView textField:(UITextField*) textField
{
CGRect pickerFrame = CGRectMake(0, 0, 200, 216);
pickerView.frame = pickerFrame;
pickerView.userInteractionEnabled = YES;
pickerView.dataSource = self;
pickerView.hidden = YES;
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
[textField setInputView:pickerView];
textField.delegate = self;
[pickerView removeFromSuperview];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [self.countryCodes objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.countryCodes count];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.delegate.selectedCountryCode = [self.countryCodes objectAtIndex:row];
NSLog(#"picker was(is): %d",[_countryPicker selectedRowInComponent:0]);
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
for (int i = 0; i < [self.countryCodes count]; i++)
{
if ([[self.countryCodes objectAtIndex:i] isEqualToString:self.delegate.selectedCountryCode]){
[_countryPicker selectRow:i inComponent:0 animated:YES];
self.countrySelectedRow = i;
break;
}
}
[_countryPicker reloadAllComponents];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
self.countryPicker.hidden = NO;
}

UIPickerView in a popover inside a Form Sheet viewController (iPad)

I have a textfield in my form sheet. When the textfield is typed on, I want a popover to appear with a pickerView inside. I've used popOverController before, but in this case I don't have a clue on how to place a pickerView and set it's delegate and datasource to the form sheet view controller, because actually the popover needs an independent view controller.
i tried the following (the app is universal), the popover isn't appearing:
- (IBAction)gradeTextfieldPressed:(UITextField *)sender
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
[self.nameTextField resignFirstResponder];
UIViewController *pickerController = [[UIViewController alloc] init];
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(self.gradeTextField.center.x, self.gradeTextField.center.y, 320, 320)];
pickerView.delegate = self;
pickerView.dataSource = self;
[pickerController.view addSubview:pickerView];
UIPopoverController *pickerPopover = [[UIPopoverController alloc] initWithContentViewController:pickerController];
[pickerPopover presentPopoverFromRect:CGRectMake(self.gradeTextField.center.x, self.gradeTextField.center.y, 320, 320) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
[self.gradeTextField setInputView:pickerView];
if ([self.gradeTextField.text isEqualToString:#""]) {
[self pickerView:pickerView didSelectRow:0 inComponent:0];
}
} else if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
[self.picker setHidden:NO];
//[self pickerView:self.picker didSelectRow:0 inComponent:0];
if ([self.gradeTextField.text isEqualToString:#""]) {
[self pickerView:self.picker didSelectRow:0 inComponent:0];
}
[self.gradeTextField setInputView:self.picker];
[self.nameTextField resignFirstResponder];
[self.creditstextField resignFirstResponder];
[self.chaptersTextField resignFirstResponder];
}
}
One way to do this that I found simple Create a new controller with just the PickerView in it (in this case done with a .xib), and have a simple delegate protocol to let your form sheet controller know when something has been picked.
#protocol MyPickerDelegate <NSObject>
- (void)valuePicked:(NSString*)value
#end
#interface MyPickerController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
__weak IBOutlet UIPickerView *_pickerView;
}
#property (nonatomic, weak) id<MyPickerDelegate> delegate;
You can then implement the data source and delegate methods in this controller. Here would be the code for when the item was picked:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[_delegate valuePicked:[_myStrings objectAtIndex:row]];
}
And finally, in the calling class (your form sheet controller):
- (void)displayPickerFromRect:(CGRect)rect inView:(UIView*)view
{
if (!_pickerController)
_pickerController = [[MyPickerController alloc] initWithNibName:nil bundle:nil];
if (_pickerController)
{
_speedPickerController.delegate = self;
if (!_pickerPopover)
{
_pickerPopover = [[UIPopoverController alloc] initWithContentViewController:_pickerController];
_pickerPopover.popoverContentSize = _pickerController.view.frame.size;
_pickerPopover.delegate = self;
}
[_pickerPopover presentPopoverFromRect:rect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
if (_pickerController)
{
_pickerController = nil;
_pickerPopover = nil;
}
}
- (void)valuePicked:(NSString*)value
{
// do something with the picked value
// dismiss the popover if you want it to go away as soon as a value is picked
}

iOS partial screen dialog for drop down listbox (android spinner) style control

In iOS for the iPhone I want to make a control with similar appearance and behavior to the android spinner control when configured to behave like a drop down list box. Specifically when pressed a modal list of text options with radio buttons comes up and when one of them is pressed the list disappears and the control updates to that choice. Example:
So far I have seen a full-screen option using [self presentViewController...] with a custom ViewController but I want a partial screen (like pictured above) solution. Does anyone know how to do this or could point in the right direction.
The native solution to this will be a UIActionSheet which on iPhone will appear from the bottom and be partial screen or on iPad be very similar to the android version.
You can find the documentation here: UIActionSheet
if you didnt want to use the UIActionSheet and you wanted to make it reusable rather than adding a whole bund of UIViews to your current XIB, you could create a custom UIView with whatever interface you would need to populate it and use the interface builder to help make it look ok.
that view could have a message handler that posts the response that you would need to listen for.
then just init and load the view into your subviews and populate it
then post a message from the custom view to the handler you registered
so for your custom view you would have something like this.
#implementation SomeCustomView
+(SomeCustomView*)viewFromNibNamed:(NSString *)nibName{
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
SomeCustomView *customView = nil;
NSObject* nibItem = nil;
while ((nibItem = [nibEnumerator nextObject]) != nil) {
if ([nibItem isKindOfClass:[AADropDown class]]) {
customView = (SomeCustomView*)nibItem;
break;
}
}
return customView;
}
-(void)someInitializationWith:(NSArray*)repeatableData andNotificationId:(NSString*)noteId{
//set your stuff up for the view here and save the notification id
}
...
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[[NSNotificationCenter defaultCenter] postNotificationName:Your_Notification_Id object:somevalue];
}
#end
and include other things, like in this case the tableview stuff or any other logic.
then in your viewcontroller you could call it like
__block id observer = [[NSNotificationCenter defaultCenter] addObserverForName:#"customViewAction" object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) {
//deal with notification here
[[NSNotificationCenter defaultCenter] removeObserver: observer];
}];
SomeCustomView *cv =(SomeCustomView*) [SomeCustomView viewFromNibNamed:#"SomeCustomView"];
[cv someInitializationWith:arrayOptions andNotificationId:#"customViewAction"];
[self.view addSubview:cv];
and in your interface builder you will just need to make sure that the class of the view is set to your class type.
then you can easily reuse this code again whenever a user needs to select something else in the same manner.
Here is a variation on the solution suggested by AtomRiot.
On your view (xib or storyboard) make a button and assign this graphic to it. Don't worry if it appears stretched out in the editor. The code will make it a realizable graphic.
2X version
Then include the following files in your project (copied below):
DDLBHelper.h
DDLBHelper.m
Then in your ViewController's .h file make links to the button:
#property (weak, nonatomic) IBOutlet UIButton *ddlbB;
- (IBAction)ddlbBClick:(id)sender;
In you ViewController's .m file make the following calls:
#synthesize ddlbB, choiceLabel;
DDLBHelper *mDDLBH;
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *strings = [[NSArray alloc] initWithObjects:#"Item 1", #"Item 2", #"Item 3", nil];
mDDLBH = [[DDLBHelper alloc] initWithWithViewController:self button:ddlbB stringArray:strings currentValue:1];
}
- (IBAction)ddlbBClick:(id)sender {
[mDDLBH popupList];
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
[mDDLBH adjustToRotation];
}
Works just like android.
Here are the files:
DDLBHelper.h
// DDLBHelper.h
// Created by MindSpiker on 9/27/12.
#import <Foundation/Foundation.h>
#protocol DDLBHelperDelegate <NSObject>
#required
- (void) itemSelected: (int)value;
#end
#interface DDLBHelper : UIViewController <UITableViewDelegate, UITableViewDataSource>{
id <DDLBHelperDelegate> delegate;
}
#property (retain) id delegate;
// external interface
- (id) init;
- (id) initWithWithViewController:(UIViewController *)viewController button:(UIButton *)button stringArray:(NSArray *)values currentValue:(int) currentValue;
- (void) popupList;
- (BOOL) isShown;
- (void) adjustToRotation;
- (int) getValue;
- (NSString *)getValueText;
#end
DDLBHelper.m
// DDLBHelper.m
// Created by MindSpiker on 9/27/12.
#import "DDLBHelper.h"
#import <QuartzCore/QuartzCore.h>
#interface DDLBHelper () {
#private
UIViewController *mVC;
UIButton *mButton;
NSArray *mValues;
int mValue;
UITableView *mTV;
UIView *mBackgroundV;
}
#end
#implementation DDLBHelper
#synthesize delegate;
- (id) init {
self = [super init];
mVC = nil;
mButton = nil;
mValues = nil;
mValue = -1;
return self;
}
- (id) initWithWithViewController:(UIViewController *)viewController button:(UIButton *)button stringArray:(NSArray *)values currentValue:(int) currentValue {
self = [super init];
// save pointers
mVC = viewController;
mButton = button;
mValues = values;
mValue = currentValue;
[self setupButton];
return self;
}
- (void) popupList{
if (mBackgroundV == nil){
mBackgroundV = [self setupBackgroundView];
[mVC.view addSubview:mBackgroundV];
}
if (mTV == nil){
mTV = [self setupTableView];
[mVC.view addSubview:mTV];
}
[mTV reloadData];
[mBackgroundV setHidden:NO];
[mTV setHidden:NO];
}
- (BOOL) isShown{
return !mTV.isHidden;
}
- (void) adjustToRotation{
BOOL isShown = [self isShown];
// remove the controls
if (mBackgroundV != nil){
[mBackgroundV removeFromSuperview];
mBackgroundV = nil;
}
if (mTV != nil){
[mTV removeFromSuperview];
mTV = nil;
}
if (isShown){
[self popupList];
}
}
- (int) getValue{
return mValue;
}
- (NSString *) getValueText{
if (mValues != nil && mValue > -1) {
if (mValues.count > mValue){
return [mValues objectAtIndex:mValue];
}
}
return nil;
}
- (void) updateButtonTitle{
NSString *title = [NSString stringWithFormat:#" %#", [self getValueText]];
[mButton setTitle:title forState:UIControlStateNormal];
}
- (void) setupButton {
UIImage *buttonBG = [UIImage imageNamed:#"sis_proceeds_ddlb.png"];
UIEdgeInsets insets = UIEdgeInsetsMake(8, 8, 8, 45);
UIImage *sizableImg = [buttonBG resizableImageWithCapInsets:insets];
[mButton setBackgroundImage:sizableImg forState:UIControlStateNormal];
[mButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[self updateButtonTitle];
}
- (UIView *) setupBackgroundView{
UIView *v = [[UIView alloc] initWithFrame:mVC.view.bounds];
[[v layer] setOpaque:NO];
[[v layer] setOpacity:0.7f];
[[v layer] setBackgroundColor:[UIColor blackColor].CGColor];
return v;
}
- (UITableView *) setupTableView {
CGRect rect = [self makeTableViewRect];
UITableView *tv = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
[tv setDelegate:self];
[tv setDataSource:self];
[tv setBackgroundColor:[UIColor whiteColor]];
[[tv layer] setBorderWidth:2];
[[tv layer] setBorderColor:[UIColor lightGrayColor].CGColor];
[[tv layer] setCornerRadius:10];
[mVC.view addSubview:tv];
return tv;
}
- (CGRect) makeTableViewRect {
float l=0.0, t=0.0, w=0.0, h=0.0, maxH=0.0, cellH=0.0, cellsH=0.0;
// get
l = mButton.frame.origin.x;
w = mButton.frame.size.width;
t = mVC.view.bounds.origin.y + 50;
maxH = mVC.view.bounds.size.height - 100;
// get cell height
UITableViewCell *c = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cellH = c.bounds.size.height;
// see if list will overlow maxH(eight)
cellsH = cellH * mValues.count;
if (cellsH > maxH) {
h = maxH;
} else {
h = cellsH;
}
return CGRectMake(l, t, w, h);
}
#pragma mark - TableView Delegate functions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1; // this is a one section table
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return mValues.count; // should be called for only one section
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// try to resuse a cell if possible
static NSString *RESUSE_IDENTIFIER = #"myResuseIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RESUSE_IDENTIFIER];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:RESUSE_IDENTIFIER];
}
cell.textLabel.text = [mValues objectAtIndex:indexPath.row];
if (mValue == indexPath.row){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// save value and hide view
mValue = indexPath.row;
[self updateButtonTitle];
[mBackgroundV setHidden:YES];
[mTV setHidden:YES];
[delegate itemSelected:mValue];
}
#end

Not able to populate PickerView with my string

I am using the inputView to display a pickerView when a a textfield is clicked. I then want to populate the pickerview with the numbers 1-100. I have some code that I thought would work, but when i run the program and click on the textField, it just pops up an empty pickerview. Also need to know how to put another button on the toolbar. I would like to have a submit button on the right side to confirm the users selection (going to change the done to cancel) Is there something I have to do in the interface builder with the picker and buttons? because i don't actually have those in the interface builder because they are made with code...
Below are my .h and .m files.
.h----
#interface TestinputviewViewController : UIViewController <UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate> {
IBOutlet UITextField *textField;
NSMutableArray *pickerViewArray;
}
-(IBAction) textFieldDidBeginEditing;
#end
.m---
#import "TestinputviewViewController.h"
#implementation TestinputviewViewController
-(IBAction)textFieldDidBeginEditing{
UIPickerView *myPickerView = [[UIPickerView alloc] init];
textField.inputView = myPickerView;
myPickerView.showsSelectionIndicator = YES;
myPickerView.delegate = self;
myPickerView.dataSource = self;
[myPickerView release];
UIToolbar *myToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(inputAccessoryViewDidFinish)];
[myToolbar setItems:[NSArray arrayWithObject:doneButton] animated:NO];
textField.inputAccessoryView = myToolbar;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)myPickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *) myPickerView numberOfRowsInComponent: (NSInteger)component {
return [pickerViewArray count];
}
-(NSString *)pikerView:(UIPickerView *) myPickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [pickerViewArray objectAtIndex:row];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
pickerViewArray = [[NSMutableArray alloc] init];
for (int i = 1; i<=20; i++) {
NSString *myString = [NSString stringWithFormat:#"%d%",i];
[pickerViewArray addObject:myString];
}
}
You are not setting delegate of picker to the current object class.
use
`myPickerView.delegate = self;`
`myPickerView.dataSource = self;`
after allocating the picker view object.
go on..

Resources