Picker On AlertView Not Visible in IOS7 - objective-c

My below code working fine in below iOS 7
I am trying to add picker view in alert that works fine in below ios7 version But in ios 7 it show white alert without picker view.
-(void)showPinPickerAlert
{
numberarr = [[NSMutableArray alloc]initWithObjects:#"0",#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9", nil];
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Enter Pin To Change Track me Option" message:#"\n\n\n\n\n\n\n" delegate:self cancelButtonTitle:#"Verify" otherButtonTitles:nil];
UIPickerView *picker=[[UIPickerView alloc]initWithFrame:CGRectMake(25, 30, 230, 60) ];
picker.dataSource=self;
picker.delegate=self;
// picker.backgroundColor=[UIColor blueColor];
picker.showsSelectionIndicator = YES;
// picker.autoresizingMask = UIViewAutoresizingFlexibleHeight;
picker.transform = CGAffineTransformMakeScale(0.6, 0.6);
alert.tag=100;
// picker.transform = CGAffineTransformMakeScale(1, 0.2);
[alert addSubview:picker];
[alert show];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 4;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
strPin=[[NSString stringWithFormat:#"%i%i%i%i",[pickerView selectedRowInComponent:0],[pickerView selectedRowInComponent:1],[pickerView selectedRowInComponent:2],[pickerView selectedRowInComponent:3]]mutableCopy];
NSLog(#"strPin=%#",strPin);
// mlabel.text= [arrayNo objectAtIndex:row];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
return [numberarr count];
}
**//code try to change color of picker text and background thats work fine in below ios7 but in iOS 7 still shows white screen**
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *label = (UILabel*) view;
if (label == nil)
{
label = [[UILabel alloc] init];
}
//[label setText:#"Whatever"];
// This part just colorizes everything, since you asked about that.
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor blackColor]];
CGSize rowSize = [pickerView rowSizeForComponent:component];
CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
[label setFrame:labelRect];
return label;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
pickerView.backgroundColor=[UIColor blackColor];
return [numberarr objectAtIndex:row];
}
OutPut in below
Output in IOS 7
How to fix it?

Adding subviews to a UIAlertView is not supported anymore, starting in iOS7.
You should implement your own view and try to do it similar to the alert view, or like other person said, use a 3rd party alert view like this one:
https://github.com/wimagguc/ios-custom-alertview

Most of the following code is from pre ios7 stack overflow answers.
PickerPrompt.h
#import <UIKit/UIKit.h>
#interface PickerPrompt : UIAlertView <UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate>
{
UIPickerView *_pickerView;
NSMutableArray *_options;
}
#property (readonly) NSString *enteredText;
- (id)initWithTitle:(NSString *)title message:(NSString *)message options:(NSMutableArray*)options delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okButtonTitle;
#end
pickerPrompt.m
#import "PickerPrompt.h"
#implementation PickerPrompt
#define VIEW_TAG 49
#define SUB_LABEL_TAG 52
#define LABEL_TAG 53
#define COMPONENT_WIDTH 250
#define LABEL_WIDTH 10
#synthesize enteredText;
- (id)initWithTitle:(NSString *)title message:(NSString *)message options:(NSMutableArray*)options delegate:(id)delegate cancelButtonTitle:(NSString *)cancelButtonTitle okButtonTitle:(NSString *)okayButtonTitle
{
if (self = [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:okayButtonTitle, nil])
{
_options = options;
_pickerView = [[UIPickerView alloc] init];
[_pickerView sizeToFit];
[_pickerView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
[_pickerView setDelegate:self];
[_pickerView setDataSource:self];
[_pickerView setShowsSelectionIndicator:TRUE];
// Change from pre iOS 7
[self setAlertViewStyle:UIAlertViewStylePlainTextInput];
[[self textFieldAtIndex:0] setDelegate:self];
[[self textFieldAtIndex:0] setInputView:_pickerView];
[[self textFieldAtIndex:0] becomeFirstResponder];
}
return self;
}
#pragma mark -
#pragma mark Picker delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (pickerView == _pickerView) {
return [_options count];
}
return [_options count];
}
- (UIView *)labelCellWithWidth:(CGFloat)width rightOffset:(CGFloat)offset {
// Create a new view that contains a label offset from the right.
CGRect frame = CGRectMake(0.0, 0.0, width, 32.0);
UIView *view = [[[UIView alloc] initWithFrame:frame] autorelease];
view.tag = VIEW_TAG;
frame.size.width = width - offset;
UILabel *subLabel = [[UILabel alloc] initWithFrame:frame];
subLabel.textAlignment = UITextAlignmentRight;
subLabel.backgroundColor = [UIColor clearColor];
subLabel.font = [UIFont systemFontOfSize:24.0];
subLabel.userInteractionEnabled = NO;
subLabel.tag = SUB_LABEL_TAG;
[view addSubview:subLabel];
[subLabel release];
return view;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *fullString = [[textField text] stringByAppendingString:string];
for (NSString* object in _options) {
if ([object isEqualToString:fullString]) {
return YES;
}
}
return NO;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
UIView *returnView = nil;
if ((view.tag == VIEW_TAG) || (view.tag == LABEL_TAG)) {
returnView = view;
}
else {
returnView = [self labelCellWithWidth:COMPONENT_WIDTH rightOffset:LABEL_WIDTH];
}
// The text shown in the component is just the number of the component.
NSString *text = [_options objectAtIndex:row];
// Where to set the text in depends on what sort of view it is.
UILabel *theLabel = nil;
if (returnView.tag == VIEW_TAG) {
theLabel = (UILabel *)[returnView viewWithTag:SUB_LABEL_TAG];
}
else {
theLabel = (UILabel *)returnView;
}
theLabel.text = text;
return returnView;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return COMPONENT_WIDTH;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
[[self textFieldAtIndex:0] setText:[_options objectAtIndex:row]];
}
- (NSString *)enteredText
{
return [[self textFieldAtIndex:0] text];
}
#end
How to use (called from an alert view delegate):
PickerPrompt *prompt = [PickerPrompt alloc];
NSMutableArray *options = [[NSMutableArray alloc] initWithObjects:#"option 1", #"option 2", nil];
prompt = [prompt initWithTitle:#"Select Option" message:#"Select Option" options:options delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Okay"];
[prompt show];
[prompt release];

Related

Multiple Pickerview with differents values

I have 5 tables, and I have to make an UIPickerView for each one.
I created one, like this
How can I do with the 4 others table ? I have to make 4 copy of this code ?
I do not know if I'm the right way to create my UIPickerView , I would like confirmation (or not).
This is what I did (I took the code from my colleague, who is also a beginner)
This is the right way to do ?
How to adapt it if I UIPickerViews 5 ?
#property (nonatomic, strong) UITextField *pickerViewDossier;
- (void)viewDidLoad {
[super viewDidLoad];
self.pickerViewDossier = [[UITextField alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.pickerViewDossier];
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
self.pickerViewDossier.inputView = pickerView;
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:#"Valider" style:UIBarButtonItemStyleDone target:self action:#selector(doneTouched:)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Annuler" style:UIBarButtonItemStyleDone target:self action:#selector(cancelTouched:)];
[toolBar setItems:[NSArray arrayWithObjects:cancelButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], doneButton, nil]];
self.pickerViewDossier.inputAccessoryView = toolBar;
self.listeSuiviDossier = [NSArray arrayWithObjects:#"Vous-même", #"Un confrère",nil];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return listeSuiviDossier.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *titrePickerview = listeSuiviDossier[row];
return titrePickerview;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSString *titrePickerview = listeSuiviDossier[row];
[suiviDossierBouton setTitle:titrePickerview forState:UIControlStateNormal];
}
- (IBAction)suiviDossierAction:(id)sender {
[self.pickerViewDossier becomeFirstResponder];
}
- (void)cancelTouched:(UIBarButtonItem *)sender
{
[self.pickerViewDossier resignFirstResponder];
[suiviDossierBouton setTitle:#"Sélectionnez" forState:UIControlStateNormal];
}
- (void)doneTouched:(UIBarButtonItem *)sender
{
[self.pickerViewDossier resignFirstResponder];
}
Use tag for picker so that you can select what to do for each picker.
For example:
Where you are Declaring your pickers:
picker1.tag = 1
picker2.tag = 2
and for each method:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger) {
if(pickerView.tag == 1) // you can also use a switch
{
// picker 1
}
else if(pickerView.tag == 2)
{
// picker 2
}
else if(pickerView.tag == 3)
{
// picker 3
}
else if(pickerView.tag == 4)
{
// picker 4
}
}

Not to dismiss when I tap on UIPickerView

I have a UIPickerView where I have a Male and a Female option.
What I have is when I click on label, the UIPickerView is shown, and based on the selection in UIPickerView, the same text is shown on label.
All is working well, but tapping on UIPickerView is not working properly.
When I tap on UIPickerView,
For iOS6, UIPickerView gets dismissed.
For iOS7, UIPickerView DOESN'T get dismissed.
So what I wanted to do is to not dismiss UIPickerView when I click on it.
Any idea how to do that for iOS 6?
Dropbox link
Code
.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>
#property (retain, nonatomic) IBOutlet UIPickerView *myPicker;
#property (retain, nonatomic) IBOutlet UILabel *myLabel;
#property (retain, nonatomic) IBOutlet NSMutableArray *arrayGender;
#end
.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myPicker, myLabel, arrayGender;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
arrayGender = [[NSMutableArray alloc] init];
[arrayGender addObject:#"Male"];
[arrayGender addObject:#"Female"];
myLabel.text = #"Choose gender...";
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideAllKeyboards)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];
myLabel.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGestureRecognizergenderLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(genderLabelTapped)];
tapGestureRecognizergenderLabel.numberOfTapsRequired = 1;
[myLabel addGestureRecognizer:tapGestureRecognizergenderLabel];
[tapGestureRecognizergenderLabel release];
myPicker.hidden = NO;
}
-(void) genderLabelTapped {
NSLog(#"genderLabelTapped");
[myPicker reloadAllComponents];
myPicker.hidden = NO;
}
-(IBAction)hideAllKeyboards {
NSLog(#"hideAllKeyboards");
myPicker.hidden = YES;
}
- (void)viewWillAppear:(BOOL)animated
{
NSLog(#"viewWillAppear");
[super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) dealloc {
[myPicker release];
[myLabel release];
[super dealloc];
}
- (IBAction)takeMeBack:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
NSLog(#"custom data..");
if (IS_DEVICE_RUNNING_IOS_7_AND_ABOVE()) {
// NSLog(#"changing font...");
UILabel *label;
// = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 233, 44)]; // your frame, so picker gets "colored"
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 233, 44)];
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:#"Trebuchet MS" size:14];
label.textAlignment = NSTextAlignmentCenter;
label.text = [arrayGender objectAtIndex:row];
return label;
} else {
// NSLog(#"changing font...");
UILabel *label;
// = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 193, 44)];
label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 193, 44)];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:18];
label.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:14];
label.text = [arrayGender objectAtIndex:row];
return label;
}
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [arrayGender count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [arrayGender objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
myLabel.text = [NSString stringWithFormat:#"%#", [arrayGender objectAtIndex:row]];
myPicker.accessibilityValue = [NSString stringWithFormat:#"%#", [arrayGender objectAtIndex:row]];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate
{
return NO;
}
#end
I know because of gesture recognizer, picker is getting hided in iOS6. The problem is why it is not getting hided in iOS7?
Did you write this yourself if you just copy-pasted it from somewhere and you didn't know what it does so you came to Stack Overflow with close to zero research done? By close to zero research, I mean you didn't even read the code...
What do you think these lines do?
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(hideAllKeyboards)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];
-(IBAction)hideAllKeyboards {
NSLog(#"hideAllKeyboards");
myPicker.hidden = YES;
}
It turns out, when a touch happens (on the pickerview) in iOS7, the view that catches the tap is of class UIPickerTableViewWrapperCell, while in iOS6, it's of class UIPickerTableView (if not tapping on a row) or UITableViewCellContentView (when tapping on a row). My guess is, the later two let the tap pass through as if the tap happened on their superview (in your case, self.view). <- The last sentence is just a guess, not for sure.
The way you can make sure the picker only gets hidden in case the tap happened on self.view is to set a delegate self as delegate to tapGesture, then implement the gestureRecognizer:shouldReceiveTouch method:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if (touch.view == self.view) {
return YES;
} else {
return NO;
}
}

UIPickerView not scrolling

here is my code, I used Google map and UIPickerView:
-(void)loadView
{
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86 longitude:151.20 zoom:14];
mapViewCustomer = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapViewCustomer.myLocationEnabled = YES;
// mapView_ = [[GMSMapView alloc]initWithFrame:CGRectMake(0, 45, self.view.frame.size.width, self.view.frame.size.height)];
// [self.view addSubview:mapView_];
self.view = mapViewCustomer;
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
marker.title = #"My location";
;
marker.map = mapViewCustomer;
[marker setIcon:[UIImage imageNamed:#"location1.png"]];
}
and I have a UIPickerView in viewDidLoad, I tried put it on viewWillDisappear or viewWillApear but it doesn't work:
- (void)viewDidLoad
{
pickerViewCustomer = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 162.0, 320.0, 120.0)];
//[pickerViewCustomer setFrame:CGRectMake(0.0, 162.0, 320.0, 120.0)];
pickerViewCustomer.hidden = YES;
pickerViewCustomer.delegate = self;
pickerViewCustomer.dataSource = self;
pickerViewCustomer.userInteractionEnabled = NO;
arrayDistanceFilters = [[NSArray alloc] initWithObjects:#"5km",#"10km",#"50km",#"100km",#"100km",#"100km",#"100km",#"100km",#"100km",#"100km", nil];
arrayDistanceValues = [[NSArray alloc] initWithObjects:[NSNumber numberWithFloat:5], [NSNumber numberWithFloat:10],[NSNumber numberWithFloat:50], [NSNumber numberWithFloat:100], nil];
[pickerViewCustomer selectRow:1 inComponent:0 animated:NO];
[pickerViewCustomer reloadAllComponents];
[self.view addSubview:pickerViewCustomer];
}
delegate and data source
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [arrayDistanceFilters count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [arrayDistanceFilters objectAtIndex:row];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
return 40;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
}
But scrolling does not work. What is wrong with my code?
try an other position on the view...
I had also a picker, which wasnt scrolling,too, then i moved the position(in the storyboard) of the picker and it worked...
to switch off autolayout helped also!
not satisfying, but a solution...
Please check this working example for more details
working tutorial

a specific instance of insertsubview at index not working in ios 6.0

I'm testing my ios app that has a deployment target of 5.0 and a base SDK of 6.1.
Everything works fine in ios 5.0, and ios 5.1, but in ios 6.0 I'm having an issue with inserting a subview at index. The subview is a tableview and the parent view is an uialertview that was created as a special class "UIAlertTableView." The alertview appears, but there appears to be nothing inserted. Before this, I had fixed an autorotation issue of the superview (which is in landscape) because, as it is well known ios 6.0 handles rotation differently, so now my superview appears correctly, but as I said, this alertview pops up with no table now. Am I suppose to be fixing autorotation issues for the tableview as well as the superview? I didn't think this would be necessary since the tableview is not declared in the imported class, is is declared within the parent viewcontroller. Or could this be because of some method that was deprecated in ios 6.0?
/*UIAlertTableView.m (the imported object class)*/
#interface UIAlertView (private)
- (void)layoutAnimated:(BOOL)fp8;
#end
#implementation UIAlertTableView
#synthesize tableWidth;
#synthesize tableHeight;
#synthesize lowestView;
#synthesize kTablePadding;
#synthesize alertDelegate;
- (void)layoutAnimated:(BOOL)fp8 {
[super layoutAnimated:fp8];
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y - tableExtHeight/2, self.frame.size.width, self.frame.size.height + tableExtHeight)];
// We get the lowest non-control view (i.e. Labels) so we can place the table view just below
int i = 0;
while (![[self.subviews objectAtIndex:i] isKindOfClass:[UIControl class]]) {
lowestView = [self.subviews objectAtIndex:i];
i++;
}
tableWidth = 262.0f;
for (UIView *sv in self.subviews) {
// Move all Controls down
if ([sv isKindOfClass:[UIControl class]]) {
sv.frame = CGRectMake(sv.frame.origin.x, sv.frame.origin.y + tableExtHeight, sv.frame.size.width, sv.frame.size.height);
}
}
}
- (void)show{
[self prepare];
[super show];
}
- (void)prepare {
if (tableHeight == 0) {
tableHeight = 150.0f;
}
kTablePadding = 8.0f;
tableExtHeight = tableHeight + 2 * kTablePadding;
[self setNeedsLayout];
}
#end
/*the UIAlertTableView class is imported into the myViewController header file*/
/*myViewController.m*/
#implementation myViewController
#synthesize myTableView;
#synthesize alert;
#synthesize imageView;
#synthesize scrollView;
#synthesize models;
#synthesize picked;
#pragma myTableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [models count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// now configure the cell
cell.textLabel.text = [models objectAtIndex:[indexPath row]];
[cell setAccessibilityTraits: UIAccessibilityTraitButton];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (returnedSetting && (indexPath.row == prevSelectedIndex)){
returnedSetting = FALSE;
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//index path to row that's selected
NSIndexPath *myIndexPath = [myTableView indexPathForSelectedRow];
UITableViewCell *cell = [myTableView cellForRowAtIndexPath:myIndexPath];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *myIndexPath = [tableView indexPathForSelectedRow];
prevSelectedIndex = myIndexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:myIndexPath];
[alert dismissWithClickedButtonIndex:0 animated:YES];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
[self dismissModalViewControllerAnimated:YES];
}
-(void)removeButton{
[UIView animateWithDuration:1.5
delay:1.5
options:UIViewAnimationCurveEaseInOut
animations:^ {
eButton.alpha = 0;
}
completion:^(BOOL finished) {
}];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
-(void)showAlertFor:(NSTimer *)timer{
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}
-(void)bringupAlertTableViewFor:(NSString *)dName atLocationOnScreen:(CGPoint)newPoint{
if (([dName isEqualToString:#"hello"]){
picked =TRUE;
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Choose from the table below:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"dName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}else{
picked = TRUE;
frame.origin.x = newPoint.x - 29; // new x coordinate
frame.origin.y = 240; // new y coordinate
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 1.5];
[UIView commitAnimations];
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Select a choice:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:#selector(showAlertFor:) userInfo:nil repeats:NO];
previousPoint = newPoint;
}
}
-(IBAction)singleTapImageView:(UITapGestureRecognizer *)sender {
CGPoint pt = [sender locationInView: sender.view];
//find out which was pressed
if ( ((pt.x >= 52) && (pt.x <= 79)) && ((pt.y >= 269) && (pt.y <= 296))){
CGPoint newPoint = {45, (257 + 55)};
[self bringupAlertTableViewFor:#"Choice1" atLocationOnScreen:newPoint];
}
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)sView{
[self removeButton];
}
-(void)scrollViewDidScroll:(UIScrollView *)sView{
eButton.alpha = .7;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)sView
{
[self removeButton];
}
-(void)exitButtonPressed{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
UIImage *imageS = [UIImage imageNamed:#"ti.png"];
imageView = [[TouchDetectingImageView alloc]initWithImage:imageS];
[imageView setDelegate:self];
imageView.frame = CGRectMake(20, 25, imageS.size.width,imageS.size.height);
CGFloat newScrollWidth = imageView.image.size.width + 20;
[scrollView setContentSize:(CGSizeMake(newScrollWidth, imageView.image.size.height))];
[scrollView addSubview: imageView];
imageView.contentMode = UIViewContentModeScaleToFill;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapImageView:)];
singleTap.numberOfTapsRequired = 1;
[scrollView addGestureRecognizer:singleTap];
UIImage *img = [UIImage imageNamed:#"backbutton.png"];
CGRect frameForButton = CGRectMake(0, 3, img.size.width, img.size.height);
eButton = [[exitButton alloc] initWithFrame:frameForButton];
[eButton setDelegate:self];
[eButton addTarget:self action:#selector(exitButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *buttonTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(exitButtonPressed)];
buttonTap.numberOfTapsRequired = 1;
[eButton addGestureRecognizer:buttonTap];
eButton.alpha = 0;
[self.view addSubview:eButton];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewDidUnload
{
[self setScrollView:nil];
[self setImageView:nil];
[self setmyTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[scrollView flashScrollIndicators];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// The menu is only going to support landscape orientations
return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
- (NSInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
-(BOOL)shouldAutorotate{
return YES;
}
#end
The reason(s) for this were:
1) the call to layoutAnimated was being ignored
2) it appears that ios 6 handles view hierarchy somewhat differently...
3) ios 6.0 automatically scales to fit a 1136x640 display vs earlier version that scale to fit a 960x640 display.
solutions were:
use a layoutsubviews call and layoutifneeded
also using conditional statements to find the ios version (e.g. greater_than_or_equal_to ios 6.0)

Multiple UIPickers to show in action sheet

in one of my view controllers I want to use multiple pickers.
Header file:
#interface MyTableController : TTTableViewController <UIActionSheetDelegate, UIPickerViewDataSource, UIPickerViewDelegate>{
IBOutlet UIPickerView *picker1;
IBOutlet UIPickerView *picker2;
NSMutableArray *list1;
NSMutableArray *list2;
}
#property(nonatomic,retain) UIPickerView *picker1, *picker2;
-(IBAction)togglePickerView1;
-(IBAction)togglePickerView2;
#end
Implementation file:
#implementation MyTableController
#synthesize picker1, picker2;
int row_index1 = 0;
int row_index2 = 0;
- (void)locationPicker:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
if([pickerView isEqual: picker1]){
row_index1 = row;
}
if([pickerView isEqual: picker2]){
row_index2 = row;
}
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
if([pickerView isEqual: picker1]){
return 1;
}
if([pickerView isEqual: picker2]){
return 1;
}
return 0;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if([pickerView isEqual: picker1]){
return [list1 count];
}
if([pickerView isEqual: picker2]){
return [list2 count];
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component{
return [list objectAtIndex:row];
if([pickerView isEqual: picker1]){
return [list1 objectAtIndex:row];
}
if([pickerView isEqual: picker2]){
return [list2 objectAtIndex:row];
}
return nil;
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
if (actionSheet.tag == 111) {
picker1 = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
picker1.showsSelectionIndicator = YES;
picker1.dataSource = self;
picker1.delegate = self;
//Add picker to action sheet
[actionSheet addSubview:picker1];
[picker1 release];
}else if(actionSheet.tag == 222){
picker2 = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
picker2.showsSelectionIndicator = YES;
picker2.dataSource = self;
picker2.delegate = self;
//Add picker to action sheet
[actionSheet addSubview:picker2];
[picker2 release];
}
//Gets an array af all of the subviews of our actionSheet
NSArray *subviews = [actionSheet subviews];
[[subviews objectAtIndex:1] setFrame:CGRectMake(20, 266, 280, 46)];
[[subviews objectAtIndex:2] setFrame:CGRectMake(20, 317, 280, 46)];
}
-(IBAction)togglePickerView1{
UIActionSheet *asheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(#"FLT", nil) delegate:self cancelButtonTitle:NSLocalizedString(#"CANCEL", nil) destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(#"PICK", nil), nil];
[asheet setTag:111];
[asheet showInView:[self.view superview]]; //note: in most cases this would be just self.view, but because I was doing this in a tabBar Application, I use the superview.
[asheet setFrame:CGRectMake(0, 117, 320, 383)];
[asheet release];
}
-(IBAction)togglePickerView2{
//...
[asheet setTag:222];
//...
}
- (void)loadView {
[super loadView];
}
-(void)viewDidLoad{
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:#"Button1" style:UIBarButtonItemStyleBordered target:self action:#selector(togglePickerView1)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:#"Button2" style:UIBarButtonItemStyleBordered target:self action:#selector(togglePickerView2)];
NSArray *myToolbarItems = [[NSArray alloc] initWithObjects: item1, item2, nil];
[self setToolbarItems: myToolbarItems];
[myToolbarItems release];
list1 = [[NSMutableArray alloc] init];
[list1 addObject:#"--"];
[list1 addObject:#"Test1"];
list2 = [[NSMutableArray alloc] init];
[list2 addObject:#"--"];
[list2 addObject:#"Test2"];
}
#end
My problem is that no matter which button I hit, it is always the picker1 that is triggered. Any ideas where the problem is?
You are successfully creating two different pickers, and showing the correct one each time.
The problem is, each picker has the same data in it.
The first line in your data source titleForRow... method is this:
return [list objectAtIndex:row];
This ends execution of your data source method by returning a value, so both pickers will always show the same data, regardless of the rest of your code. list isn't declared anywhere in your code above so I'm not sure what you are actually seeing on the screen.
I have built a sample project using your code above and confirmed that this is the issue. Removing that line gives you two different pickers, with the different content in each one.