How to pass an array to my custom cell class - objective-c

I have a TableView with my custom cell class where I have a pickerview.
I want to pass an array to populate pickerview with data. How to pass it. Is my approach correct?

You don't pass anything to a TableViewCell. Instead you have to implement
UITableViewDelegate
UITableViewDatasource
to populate the tableView. And
UIPickerViewDelegate
UIPickerViewDatasource
for the pickers.

I have included pickerview delegate and datasource within table cell and it works fine...
Passing the array is same as to any view.
//////////////ScrollCell.h
#interface ScrollCell : UITableViewCell <UIPickerViewDataSource, UIPickerViewDelegate>{
UILabel *textlabel;
UIPickerView *pickerview;
NSString *textfieldValue;
NSString *scrollerValue;
NSArray *scrollerData;
}
#property (nonatomic,retain)UILabel *textlabel;
#property (nonatomic,retain)UIPickerView *pickerview;
#property (nonatomic,retain)NSArray *scrollerData;
#property (nonatomic,retain)NSString *textfieldValue;
#property (nonatomic,retain)NSString *scrollerValue;
-(NSString *)getTextfiledValue;
-(NSString *)getScrollerValue;
-(void)setScrollerData:(NSArray *)array;
#end
/////////ScrollerCell.m
//
// ScrollCell.m
// MultipleDetailViews
//
// Created by Ruslan Karimov on 12/5/10.
// Copyright 2010 Eventagrate. All rights reserved.
//
#import "ScrollCell.h"
#import "Answers.h"
#implementation ScrollCell
#synthesize textlabel, pickerview, scrollerData, textfieldValue, scrollerValue;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
textlabel = [[UILabel alloc]init];
textlabel.textAlignment = UITextAlignmentLeft;
textlabel.font = [UIFont systemFontOfSize:25];
textlabel.textColor =[UIColor blackColor];
[self.contentView addSubview:textlabel];
pickerview = [[UIPickerView alloc]init];
[self.contentView addSubview:pickerview];
scrollerData = [[NSArray alloc] init];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+10 ,+10, 300, 25);
textlabel.frame = frame;
//frame= CGRectMake(boundsX+200 ,0, 300, 100);
self.pickerview.frame = CGRectMake(boundsX+200 ,0, 300, 163);
self.pickerview.delegate = self;
//self.pickerview.
}
-(void)setScrollerData:(NSArray *)array
{
//[self.scrollerData arrayByAddingObjectsFromArray:array];
scrollerData = array;
NSLog(#"from scrolltable cell: %i",[self.scrollerData count]);
}
-(NSString *)getTextfiledValue
{
return self.textfieldValue;
}
-(NSString *)getScrollerValue
{
return self.scrollerValue;
}
//PICKER VIEW CONTROL
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
return [scrollerData count];
}
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
Answers *template = (Answers *)[self.scrollerData objectAtIndex:row];
return template.answer_title;
//return #"fff";
}
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
}
- (void)dealloc {
[super dealloc];
}
#end

Related

Custom delegate/protocol didnt work like it should

I've been writing an app that has custom protocol to send the data from the child view to parent view the classes is
MainViewController
AddViewController (child to mainviewcontroller)
DaysViewController (child to addviewcontroller)
the custom protocol was declared in DaysViewController and implemented in AddViewController
AddViewController.h
#import <UIKit/UIKit.h>
#import "DaysViewController.h"
#import "Course.h"
#import "Student.h"
#interface AddViewController : UITableViewController<UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIPickerViewAccessibilityDelegate,UITextFieldDelegate,DaysViewControllerDelegate>
{
NSArray *hoursarray;
UIActionSheet *aac;
IBOutlet UITextField *NameTx,*HoursTx,*DaysTx,*TimeTx;
Student *st;
Course *cc;
}
-(void) pickerDoneClick;
-(IBAction)fillTheOtherData;
#property (nonatomic ,strong) UIActionSheet *aac;
#end
AddViewController.m
#import "AddViewController.h"
#interface AddViewController ()
#end
#implementation AddViewController
#synthesize aac;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
//viewP.frame = CGRectMake(0, 154, 320, 205);
hoursarray = [[NSArray alloc]initWithObjects:#"2",#"3",#"4", nil];
[self.tableView setScrollEnabled:NO];
[DaysTx setEnabled:NO];
[TimeTx setEnabled:NO];
[HoursTx setKeyboardType:UIKeyboardTypeDecimalPad];
cc = [[Course alloc]init];
//UITapGestureRecognizer *tapgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapped:)];
//[self.view addGestureRecognizer:tapgr];
}
-(void)tapped:(UITapGestureRecognizer *)tap
{
[self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [hoursarray count];
}
//-(IBAction)addCourse
//{
// [UIView beginAnimations:#"view" context:nil];
// [UIView setAnimationDuration:1];
// viewP.frame = CGRectMake(0, 500, 320, 205);
// [UIView commitAnimations];
//
//}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [hoursarray objectAtIndex:row];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 3)
{
aac = [[UIActionSheet alloc]initWithTitle:#"How many ?" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
UIPickerView *picker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, 0, 0)];
picker.delegate = self;
picker.dataSource = self;
UIToolbar *pickerToolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[pickerToolBar 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(pickerDoneClick)];
[barItems addObject:doneBtn];
[pickerToolBar setItems:barItems animated:YES];
[aac addSubview:pickerToolBar];
[aac addSubview:picker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0, 0, 320, 464)];
}
else if (indexPath.row == 2)
{
DaysViewController *days = [self.storyboard instantiateViewControllerWithIdentifier:#"Days"];
days.delegate = self;
[self.navigationController pushViewController:days animated:YES];
}
}
-(void) pickerDoneClick
{
[aac dismissWithClickedButtonIndex:0 animated:YES];
}
-(void)chooseDays:(DaysViewController *)controller withArray:(NSArray *)theDaysArray
{
NSLog(#"I'm # chooseDays method");
NSLog(#"Before the add !!");
NSLog(#"chooseDays Method and the array is %#",theDaysArray);
cc.days = [NSMutableArray arrayWithObject:theDaysArray];
NSLog(#"After the add");
NSLog(#"chooseDays Method and the array is %#",cc.days);
// [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)cancelChooseDays:(DaysViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)fillTheOtherData
{
cc.name = NameTx.text;
cc.hour = [HoursTx.text integerValue];
NSLog(#"The name is %# and the hour credit is %d",cc.name,cc.hour);
}
#end
DaysViewController.h
#import <UIKit/UIKit.h>
#import "Course.h"
#class DaysViewController;
#protocol DaysViewControllerDelegate <NSObject>
#required
-(void)chooseDays:(DaysViewController *)controller withArray:(NSArray *)theDaysArray;
-(void)cancelChooseDays:(DaysViewController *)controller;
#end
#interface DaysViewController : UITableViewController
{
Course *courseDays;
NSArray *days;
NSMutableArray *dayChosen;
}
#property (nonatomic,weak) id<DaysViewControllerDelegate> delegate;
-(IBAction)done:(id)sender;
-(IBAction)cancel:(id)sender;
#end
DaysViewController.m
#import "DaysViewController.h"
#interface DaysViewController ()
#end
#implementation DaysViewController
#synthesize delegate;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
days = [[NSArray alloc]initWithObjects:#"Saturday",#"Sunday",#"Monday",#"Teusday",#"Wednesday",#"Thursday",#"Friday", nil];
dayChosen = [[NSMutableArray alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [days count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DaysCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DaysCell"];
}
cell.textLabel.text = [days objectAtIndex:indexPath.row];
return cell;
}
-(IBAction)done:(id)sender
{
//Course *course = [[Course alloc]init];
//[course.days addObject:dayChosen];
//NSArray *daysArray = [NSArray arrayWithObject:dayChosen];
NSLog(#"The Days are %#",dayChosen);
[self.delegate chooseDays:self withArray:dayChosen];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)cancel:(id)sender
{
[self.delegate cancelChooseDays:self];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[dayChosen addObject:[days objectAtIndex:indexPath.row]];
NSLog(#"Days are %#",dayChosen);
}
#end
MainViewController has a button that take me to AddViewController and AddViewController has same button that takes me to DaysViewController , all the views has a UITableView .
what I want to do is when I send the data from DaysViewController to AddViewController to put it in an array and dismiss the view AddViewController should show up but instead MainViewController shows and this is what I dont want it to be.
AddViewController and DaysViewController have a UINavigationController but MainViewController doesn't.
Thank you in advance.
Okay, I think I know what your problem is. In your cancel function, try and switch this line of code:
[self dismissViewControllerAnimated:YES completion:nil];
With this line of code:
[self.navigationController popViewControllerAnimated:YES];
Let me know if that helps.

Adding a UI Picker to a UITextView

I'm trying to add a UIPicker to a UITextView when it is selected to choose an age. I found a previous thread and trued to implement the code but I can't get it to work properly. When I build the program the picker shows up, but there are no values in it. Any ideas as to what I'm doing wrong? Also, I'm getting two yellow errors here saying "Assigning to 'id' from incompatible type 'ViewController *const __strong" here:
pickerView.delegate = self;
pickerView.dataSource = self;
Thank you.
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *ageTextField;
#end
#implementation ViewController
#synthesize ageTextField;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIPickerView *pickerView =[[UIPickerView alloc]init];
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator=YES;
ageTextField.inputView=pickerView;
}
- (void)pickerView:(UIPickerView *)PickerView
didSelectRow:(NSInteger)row
inComponent:(NSInteger)component {
NSMutableArray *ageArray = [[NSMutableArray alloc]init];
[ageArray addObject:#"1"];
[ageArray addObject:#"2"];
[ageArray addObject:#"3"];
[ageArray addObject:#"4"];
ageTextField.text=[ageArray objectAtIndex:row];
}
#interface ViewController () <UIPickerViewDataSource, UIPickerViewDelegate>
#property (strong, nonatomic) UIPickerView *pickerView;
#property (strong, nonatomic) NSArray *pickerElements;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.pickerView = [[UIPickerView alloc] init];
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
self.pickerView.showsSelectionIndicator = YES;
self.ageTextField.inputView = self.pickerView;
self.pickerElements = #[#"text1", #"text2", #"text3", #"text4"];
[self pickerView:self.pickerView
didSelectRow:0
inComponent:0];
}
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.pickerElements count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [self.pickerElements objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.ageTextField.text = [self.pickerElements objectAtIndex:row];
}
#end

message send to deallocated instance

I am trying to sort memory problems in my program.
My program stops at the line:
label.text = [[[[self.allData objectAtIndex:indexPath.row-1]objectAtIndex:1+[[self.measurments objectAtIndex:(i-1)]intValue]]objectAtIndex:1]stringValue];
whit mesage:
Thread 1: EXC_BREAKPOINT
** -[CFNumber stringValue]: message sent to deallocated instance 0x859add0
I have property for allData and measurments
#property (nonatomic, retain) NSMutableArray *allData;
#property (nonatomic, retain) NSMutableArray *measurments;
and I defined allData as :
self.allData = [[[NSMutableArray alloc] init]autorelease];
self.allData = [self GetTableOfLevel:TableLevel section:TableSection perent:0 array:self._backupData];
where GetTableOfLevel:TableLevel function return NSMutableArray.
after that I leave allData as it is, except i copy it as:
self.backupData = [[self.allData copy]autorelease];
Have any one any idea what it might go wrong?
I tried the advice and switch to ARC, but I have some problem whit downloaded library.
I have SBTableAlert which look like:
//
// --------------------------------------------
// Copyright (C) 2011 by Simon Blommegård
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// --------------------------------------------
//
// SBTableAlert.h
// SBTableAlert
//
// Created by Simon Blommegård on 2011-04-08.
// Copyright 2011 Simon Blommegård. All rights reserved.
//
#import <Foundation/Foundation.h>
#define kTableCornerRadius 5.
typedef enum {
SBTableAlertTypeSingleSelect, // dismiss alert with button index -1 and animated (default)
SBTableAlertTypeMultipleSelct, // dismiss handled by user eg. [alert.view dismiss...];
} SBTableAlertType;
typedef enum {
SBTableAlertStylePlain, // plain white BG and clear FG (default)
SBTableAlertStyleApple, // same style as apple in the alertView for slecting wifi-network (Use SBTableAlertCell)
} SBTableAlertStyle;
// use this class if you would like to use the custom section headers by yourself
#interface SBTableViewSectionHeaderView : UIView {}
#property (nonatomic, copy) NSString *title;
#end
#interface SBTableAlertCell : UITableViewCell {}
- (void)drawCellBackgroundView:(CGRect)r;
#end
#class SBTableAlert;
#protocol SBTableAlertDelegate <NSObject>
#optional
- (CGFloat)tableAlert:(SBTableAlert *)tableAlert heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableAlert:(SBTableAlert *)tableAlert didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableAlertCancel:(SBTableAlert *)tableAlert;
- (void)tableAlert:(SBTableAlert *)tableAlert clickedButtonAtIndex:(NSInteger)buttonIndex;
- (void)willPresentTableAlert:(SBTableAlert *)tableAlert;
- (void)didPresentTableAlert:(SBTableAlert *)tableAlert;
- (void)tableAlert:(SBTableAlert *)tableAlert willDismissWithButtonIndex:(NSInteger)buttonIndex;
- (void)tableAlert:(SBTableAlert *)tableAlert didDismissWithButtonIndex:(NSInteger)buttonIndex;
#end
#protocol SBTableAlertDataSource <NSObject>
#required
- (UITableViewCell *)tableAlert:(SBTableAlert *)tableAlert cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableAlert:(SBTableAlert *)tableAlert numberOfRowsInSection:(NSInteger)section;
#optional
- (NSInteger)numberOfSectionsInTableAlert:(SBTableAlert *)tableAlert; // default 1
- (NSString *)tableAlert:(SBTableAlert *)tableAlert titleForHeaderInSection:(NSInteger)section;
#end
#interface SBTableAlert : NSObject <UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate> {}
#property (nonatomic, retain) UIAlertView *view;
#property (nonatomic, retain) UITableView *tableView;
#property (nonatomic) SBTableAlertType type;
#property (nonatomic) SBTableAlertStyle style;
#property (nonatomic) NSInteger maximumVisibleRows; // default 4, (nice in both orientations w/ rowHeigh == 40), if -1 is passed it will display the whole table.
#property (nonatomic) CGFloat rowHeight; // default 40, (default in UITableView == 44)
#property (nonatomic, assign) id <SBTableAlertDelegate> delegate;
#property (nonatomic, assign) id <SBTableAlertDataSource> dataSource;
#property (nonatomic, assign) id <UITableViewDelegate> tableViewDelegate; // default self, (set other for more advanded use)
#property (nonatomic, assign) id <UITableViewDataSource> tableViewDataSource; // default self, (set other for more advanded use)
#property (nonatomic, assign) id <UIAlertViewDelegate> alertViewDelegate; // default self, (set other for more advanded use)
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)message, ...;
+ (id)alertWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)message, ...;
- (void)show;
#end
//
// --------------------------------------------
// Copyright (C) 2011 by Simon Blommegård
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// --------------------------------------------
//
// SBTableAlert.m
// SBTableAlert
//
// Created by Simon Blommegård on 2011-04-08.
// Copyright 2011 Simon Blommegård. All rights reserved.
//
#import "SBTableAlert.h"
#import <QuartzCore/QuartzCore.h>
#interface SBTableViewTopShadowView : UIView {}
#end
#implementation SBTableViewTopShadowView
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
// Draw top shadow
CGFloat colors [] = {
0, 0, 0, 0.4,
0, 0, 0, 0,
};
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;
CGPoint startPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds));
CGPoint endPoint = CGPointMake(CGRectGetMidX(self.bounds), 8);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;
}
#end
#interface SBTableView : UITableView {}
#property (nonatomic) SBTableAlertStyle alertStyle;
#end
#implementation SBTableView
#synthesize alertStyle=_alertStyle;
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
if (_alertStyle == SBTableAlertStyleApple) {
// Draw background gradient
CGFloat colors [] = {
0.922, 0.925, 0.933, 1,
0.749, 0.753, 0.761, 1,
};
CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
CGColorSpaceRelease(baseSpace), baseSpace = NULL;
CGPoint startPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMinY(self.bounds));
CGPoint endPoint = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMaxY(self.bounds));
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient), gradient = NULL;
}
[super drawRect:rect];
}
#end
#interface SBTableAlertCellBackgroundView : UIView
#end
#implementation SBTableAlertCellBackgroundView
- (void)drawRect:(CGRect)r {
[(SBTableAlertCell *)[self superview] drawCellBackgroundView:r];
}
#end
#implementation SBTableViewSectionHeaderView
#synthesize title=_title;
- (id)initWithTitle:(NSString *)title {
if ((self = [super initWithFrame:CGRectZero])) {
[self setTitle:title];
[self setBackgroundColor:[UIColor colorWithRed:0.165 green:0.224 blue:0.376 alpha:0.85]];
}
return self;
}
- (void)dealloc {
[self setTitle:nil];
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
[[UIColor colorWithWhite:0 alpha:0.8] set];
[_title drawAtPoint:CGPointMake(10, 4) withFont:[UIFont boldSystemFontOfSize:12]];
[[UIColor whiteColor] set];
[_title drawAtPoint:CGPointMake(10, 5) withFont:[UIFont boldSystemFontOfSize:12]];
CGContextSetLineWidth(context, 1.5);
[[UIColor colorWithWhite:1 alpha:0.35] set];
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, self.bounds.size.width, 0);
CGContextStrokePath(context);
[[UIColor colorWithWhite:0 alpha:0.35] set];
CGContextMoveToPoint(context, 0, self.bounds.size.height);
CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height);
CGContextStrokePath(context);
}
#end
#interface SBTableAlertCell ()
#property (nonatomic, retain) SBTableAlertCellBackgroundView *cellBackgroundView;
#end
#implementation SBTableAlertCell
#synthesize cellBackgroundView = _cellBackgroundView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
CGRect frame = CGRectMake(0.0, 0.0, self.contentView.bounds.size.width, self.contentView.bounds.size.height);
_cellBackgroundView = [[SBTableAlertCellBackgroundView alloc] initWithFrame:frame];
[_cellBackgroundView setBackgroundColor:[UIColor clearColor]];
[_cellBackgroundView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
[self setBackgroundView:_cellBackgroundView];
[_cellBackgroundView release];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(setNeedsDisplay) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (void)layoutSubviews {
[super layoutSubviews];
float editingOffset = 0.;
if (self.editing)
editingOffset = -self.contentView.frame.origin.x;
_cellBackgroundView.frame = CGRectMake(editingOffset,
_cellBackgroundView.frame.origin.y,
self.frame.size.width - editingOffset,
_cellBackgroundView.frame.size.height);
[self.textLabel setBackgroundColor:[UIColor clearColor]];
[self.detailTextLabel setBackgroundColor:[UIColor clearColor]];
[self setBackgroundColor:[UIColor clearColor]];
[self setNeedsDisplay];
}
- (void)setNeedsDisplay {
[super setNeedsDisplay];
[_cellBackgroundView setNeedsDisplay];
}
- (void)drawCellBackgroundView:(CGRect)r {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.5);
[[UIColor colorWithWhite:1 alpha:0.8] set];
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, self.bounds.size.width, 0);
CGContextStrokePath(context);
[[UIColor colorWithWhite:0 alpha:0.35] set];
CGContextMoveToPoint(context, 0, self.bounds.size.height);
CGContextAddLineToPoint(context, self.bounds.size.width, self.bounds.size.height);
CGContextStrokePath(context);
}
#end
#interface SBTableAlert ()
#property (nonatomic, retain) SBTableViewTopShadowView *shadow;
#property (nonatomic, assign) BOOL presented;
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)format args:(va_list)args;
- (void)increaseHeightBy:(CGFloat)delta;
- (void)layout;
#end
#implementation SBTableAlert
#synthesize view=_alertView;
#synthesize tableView=_tableView;
#synthesize type=_type;
#synthesize style=_style;
#synthesize maximumVisibleRows=_maximumVisibleRows;
#synthesize rowHeight=_rowHeight;
#synthesize delegate=_delegate;
#synthesize dataSource=_dataSource;
#dynamic tableViewDelegate;
#dynamic tableViewDataSource;
#dynamic alertViewDelegate;
#synthesize shadow = _shadow;
#synthesize presented = _presented;
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)format args:(va_list)args {
if ((self = [super init])) {
NSString *message = format ? [[[NSString alloc] initWithFormat:format arguments:args] autorelease] : nil;
_alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil];
_maximumVisibleRows = 4;
_rowHeight = 40.;
_tableView = [[SBTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
[_tableView setDelegate:self];
[_tableView setDataSource:self];
[_tableView setBackgroundColor:[UIColor whiteColor]];
[_tableView setRowHeight:_rowHeight];
[_tableView setSeparatorColor:[UIColor lightGrayColor]];
[_tableView.layer setCornerRadius:kTableCornerRadius];
[_alertView addSubview:_tableView];
_shadow = [[SBTableViewTopShadowView alloc] initWithFrame:CGRectZero];
[_shadow setBackgroundColor:[UIColor clearColor]];
[_shadow setHidden:YES];
[_shadow.layer setCornerRadius:kTableCornerRadius];
[_shadow.layer setMasksToBounds:YES];
[_alertView addSubview:_shadow];
[_alertView bringSubviewToFront:_shadow];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(layoutAfterSomeTime) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
return self;
}
- (id)initWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)message, ... {
va_list list;
va_start(list, message);
self = [self initWithTitle:title cancelButtonTitle:cancelTitle messageFormat:message args:list];
va_end(list);
return self;
}
+ (id)alertWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelTitle messageFormat:(NSString *)message, ... {
return [[[SBTableAlert alloc] initWithTitle:title cancelButtonTitle:cancelTitle messageFormat:message] autorelease];
}
- (void)dealloc {
[self setTableView:nil];
[self setView:nil];
[self setShadow:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark -
- (void)show {
[_tableView reloadData];
[_alertView show];
}
#pragma mark - Properties
- (void)setStyle:(SBTableAlertStyle)style {
if (style == SBTableAlertStyleApple) {
[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[(SBTableView *)_tableView setAlertStyle:SBTableAlertStyleApple];
[_shadow setHidden:NO];
} else if (style == SBTableAlertStylePlain) {
[_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[(SBTableView *)_tableView setAlertStyle:SBTableAlertStylePlain];
[_shadow setHidden:YES];
}
_style = style;
}
- (id<UITableViewDelegate>)tableViewDelegate {
return _tableView.delegate;
}
- (void)setTableViewDelegate:(id<UITableViewDelegate>)tableViewDelegate {
[_tableView setDelegate:tableViewDelegate];
}
- (id<UITableViewDataSource>)tableViewDataSource {
return _tableView.dataSource;
}
- (void)setTableViewDataSource:(id<UITableViewDataSource>)tableViewDataSource {
[_tableView setDataSource:tableViewDataSource];
}
- (id<UIAlertViewDelegate>)alertViewDelegate {
return _alertView.delegate;
}
- (void)setAlertViewDelegate:(id<UIAlertViewDelegate>)alertViewDelegate {
[_alertView setDelegate:alertViewDelegate];
}
#pragma mark - Private
- (void)increaseHeightBy:(CGFloat)delta {
CGPoint c = _alertView.center;
CGRect r = _alertView.frame;
r.size.height += delta;
_alertView.frame = r;
_alertView.center = c;
_alertView.frame = CGRectIntegral(_alertView.frame);
for(UIView *subview in [_alertView subviews]) {
if([subview isKindOfClass:[UIControl class]]) {
CGRect frame = subview.frame;
frame.origin.y += delta;
subview.frame = frame;
}
}
}
- (void)layout {
CGFloat height = 0.;
NSInteger rows = 0;
for (NSInteger section = 0; section < [_tableView numberOfSections]; section++) {
for (NSInteger row = 0; row < [_tableView numberOfRowsInSection:section]; row++) {
height += [_tableView.delegate tableView:_tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
rows ++;
}
}
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat avgRowHeight = height / rows;
CGFloat resultHeigh;
if(height > screenRect.size.height) {
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
resultHeigh = screenRect.size.height - _alertView.frame.size.height - 65.;
else
resultHeigh = screenRect.size.width - _alertView.frame.size.height - 65.;
}
else if (_maximumVisibleRows == -1 || rows <= _maximumVisibleRows)
resultHeigh = _tableView.contentSize.height;
else
resultHeigh = (avgRowHeight * _maximumVisibleRows);
[self increaseHeightBy:resultHeigh];
[_tableView setFrame:CGRectMake(12,
_alertView.frame.size.height - resultHeigh - 65,
_alertView.frame.size.width - 24,
resultHeigh)];
[_shadow setFrame:CGRectMake(_tableView.frame.origin.x,
_tableView.frame.origin.y,
_tableView.frame.size.width,
8)];
}
- (void)layoutAfterSomeTime{
[NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:#selector(layout) userInfo:nil repeats:NO];
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([_delegate respondsToSelector:#selector(tableAlert:heightForRowAtIndexPath:)])
return [_delegate tableAlert:self heightForRowAtIndexPath:indexPath];
return _rowHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_type == SBTableAlertTypeSingleSelect)
[_alertView dismissWithClickedButtonIndex:-1 animated:YES];
if ([_delegate respondsToSelector:#selector(tableAlert:didSelectRowAtIndexPath:)])
[_delegate tableAlert:self didSelectRowAtIndexPath:indexPath];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if ([_dataSource respondsToSelector:#selector(tableAlert:titleForHeaderInSection:)]) {
NSString *title = [_dataSource tableAlert:self titleForHeaderInSection:section];
if (!title)
return nil;
return [[[SBTableViewSectionHeaderView alloc] initWithTitle:title] autorelease];
}
return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if ([self tableView:tableView viewForHeaderInSection:section])
return 25.;
return 0.;
}
#pragma mark -
#pragma mark UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return [_dataSource tableAlert:self cellForRowAtIndexPath:indexPath];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_dataSource tableAlert:self numberOfRowsInSection:section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if ([_dataSource respondsToSelector:#selector(numberOfSectionsInTableAlert:)])
return [_dataSource numberOfSectionsInTableAlert:self];
return 1;
}
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertViewCancel:(UIAlertView *)alertView {
if ([_delegate respondsToSelector:#selector(tableAlertCancel:)])
[_delegate tableAlertCancel:self];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if ([_delegate respondsToSelector:#selector(tableAlert:clickedButtonAtIndex:)])
[_delegate tableAlert:self clickedButtonAtIndex:buttonIndex];
}
- (void)willPresentAlertView:(UIAlertView *)alertView {
if (!_presented)
[self layout];
_presented = YES;
if ([_delegate respondsToSelector:#selector(willPresentTableAlert:)])
[_delegate willPresentTableAlert:self];
}
- (void)didPresentAlertView:(UIAlertView *)alertView {
if ([_delegate respondsToSelector:#selector(didPresentTableAlert:)])
[_delegate didPresentTableAlert:self];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([_delegate respondsToSelector:#selector(tableAlert:willDismissWithButtonIndex:)])
[_delegate tableAlert:self willDismissWithButtonIndex:buttonIndex];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
_presented = NO;
if ([_delegate respondsToSelector:#selector(tableAlert:didDismissWithButtonIndex:)])
[_delegate tableAlert:self didDismissWithButtonIndex:buttonIndex];
}
#end
I put -fno-objc-arc flag on it, but when I tried open it it gave me an
*** -[SBTableAlert tableView:cellForRowAtIndexPath:]: message sent to deallocated instance 0x816b8c0
error
I open it as :
SBTableAlert *alert;
alert = [[SBTableAlert alloc] initWithTitle:NSLocalizedString(#"servers", nil) cancelButtonTitle:NSLocalizedString(#"cancel", nil) messageFormat:nil];
[alert setDelegate:self];
[alert setDataSource:self];
[alert.view setTag:1];
[alert show];
Anyone know how to deal with it?
Holy run-on sentence, Batman! Try breaking up those nested method calls into multiple lines as it'll make the code more readable.
Given that the final expression was the one generating the error message, it looks like an object in one of your arrays -- a leaf node / data object -- was over-released.
Thus, the fault lies at whatever creates the array.
BTW: Methods should always start with lower case letters and should never be prefixed with get. Thus, that method would be tableFromLevel:section:parent:array: or something similar. By convention, get* as a prefix is reserved for methods that return stuff by reference. Accessors are not prefixed with get, either.
Also and indicated in the comments, there is no need to create an empty array, assign it to self.allData and then immediately overwrite it. Not a leak because of the autorelease, but no point in doing that.
First, build and analyze your code. Fix Anything that it complains about.
Next, if the crash is still happening, use the Allocations instrument and turn on Zombie detection. It should allow you to see the retains/releases sent to the object that is crashing.

Text Box Picker

Im practicing using a picker to input values into a text field. Ive tried to adapt some code found on here to present a picker when text box is touched to fill out text field. The text boxes were built in code SOURCE and I would like to build the text boxes in IB. However this has stopped the presentation picker view, and presents only the keyboard now instead
Perhaps someone would point me in the right direction here. My code:
.h
#import <UIKit/UIKit.h>
#interface pick2 : UIViewController
<UIPickerViewDelegate, UIPickerViewDataSource> {
UIPickerView *locationsPicker;
UIToolbar *accessoryView;
UITextField *text1;
NSArray *locations;
}
#property (nonatomic, readonly) UIPickerView *locationsPicker;
#property (nonatomic, readonly) UIToolbar *accessoryView;
#property (strong, nonatomic) IBOutlet UITextField *text1;
- (void)onLocationSelection;
#end
.m
#import "pick2.h"
#interface pick2 ()
#end
#implementation pick2
#synthesize text1;
- (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:UIBarButtonItemStylePlain
target:self
action:#selector(onLocationSelection)];
[accessoryView setItems:[NSArray arrayWithObject:doneButton]];
}
return accessoryView;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)onLocationSelection {
NSInteger row = [self.locationsPicker selectedRowInComponent:0];
( [text1 isFirstResponder] ); {
text1.text = [locations objectAtIndex:row];
[text1 resignFirstResponder];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - picker view delegate/datasource
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [locations objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
return [locations count];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
locations = [[NSArray alloc] initWithObjects:#"New York", #"Chicago", #"Memphis", #"California", #"Seattle",#"London",#"Paris", nil];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setText1:nil];
[super viewDidUnload];
}
#end
All you have to do is give the inputView of your UITextField as object of your pickerview.
text1.inputView = locationsPicker;
tapping on the UITextField will present the pickerview now.
Sorted this by using IB to build text boxes and
NSInteger selectedRow = [select selectedRowInComponent:0];
text1.text = [arrStatus objectAtIndex: selectedRow];
[text1 resignFirstResponder];
To retrive text value

2 UIPickerViews each having its own UILabel to display value from NSMutableArray

I'm having 2 UIPickerViews and two UILabels in my view and the UIPickerViews are populated with numbers from an NSMutableArray.
The pickers need to send there chosen value to there assigned label. Example:
_pickerView1 (selected "18")
_pickerOutputLabel1 (shows "18")
_pickerView2 (selected "7")
_pickerOutputLabel2 (shows "7")
I can't get this working, _pickerView2 also sends its value to _pickerOutputLabel1 instead of _pickerOutputLabel2.
I've tried a couple of things but i can't figure out how to get it to work.
This is the code (i removed my attempts to fix the issue so it atleast compiles :)
//header file
#import <UIKit/UIKit.h>
#interface UIPickerViewAndLabelsViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
NSMutableArray *nrArray;
IBOutlet UIPickerView *_pickerView1;
IBOutlet UIPickerView *_pickerView2;
UILabel *_pickerOutputLabel1;
UILabel *_pickerOutputLabel2;
}
#property (nonatomic, retain) IBOutlet UIPickerView *pickerView1;
#property (nonatomic, retain) IBOutlet UIPickerView *pickerView2;
#property (nonatomic, retain) IBOutlet UILabel *pickerOutputLabel1;
#property (nonatomic, retain) IBOutlet UILabel *pickerOutputLabel2;
#end
//implementation file
#import "UIPickerViewAndLabelsViewController.h"
#implementation UIPickerViewAndLabelsViewController
#synthesize pickerView1 = _pickerView1;
#synthesize pickerView2 = _pickerView2;
#synthesize pickerOutputLabel1 = _pickerOutputLabel1;
#synthesize pickerOutputLabel2 = _pickerOutputLabel2;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
// Implement loadView to create a view hierarchy programmatically, without using a nib.
/*
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
_pickerOutputLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(400, 120, 50, 50)];
[self.view addSubview:_pickerOutputLabel1];
_pickerOutputLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(400, 320, 50, 50)];
[self.view addSubview:_pickerOutputLabel2];
nrArray = [[NSMutableArray alloc] init];
for (int i=0;i<20+1;i++) {
[nrArray addObject:[NSString stringWithFormat:#"%d", i]];
}
_pickerView1 = [[UIPickerView alloc] initWithFrame:CGRectMake(500, 120, 100, 162)];
_pickerView1.delegate = self;
_pickerView1.dataSource = self;
_pickerView1.showsSelectionIndicator = YES;
_pickerView1.transform = CGAffineTransformMakeScale(0.8, 0.8);
[self.view addSubview:_pickerView1];
[_pickerView1 release];
[_pickerView1 selectRow:0 inComponent:0 animated:NO];
_pickerOutputLabel1.text = [nrArray objectAtIndex:[_pickerView1 selectedRowInComponent:0]];
_pickerView2 = [[UIPickerView alloc] initWithFrame:CGRectMake(500, 320, 100, 162)];
_pickerView2.delegate = self;
_pickerView2.dataSource = self;
_pickerView2.showsSelectionIndicator = YES;
_pickerView2.transform = CGAffineTransformMakeScale(0.8, 0.8);
[self.view addSubview:_pickerView2];
[_pickerView2 release];
[_pickerView2 selectRow:0 inComponent:0 animated:NO];
_pickerOutputLabel2.text = [nrArray objectAtIndex:[_pickerView2 selectedRowInComponent:0]];
[super viewDidLoad];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)_pickerView1;
{
return 1;
}
- (void)pickerView:(UIPickerView *)_pickerView1 didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_pickerOutputLabel1.text= [nrArray objectAtIndex:row];
}
- (NSInteger)pickerView:(UIPickerView *)_pickerView1 numberOfRowsInComponent:(NSInteger)component;
{
return [nrArray count];
}
- (NSString *)pickerView:(UIPickerView *)_pickerView1 titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
return [nrArray objectAtIndex:row];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (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)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
I'm trying for 3 days and i'm stuck.
Thanks in advance.
In the UIPickerView delegate methods, you've named the pickerView parameter "_pickerView1". Naming that parameter the same as the instance variable does not mean the delegate method will be called only for that picker. It just becomes the local name for whatever picker calls the delegate method.
Since you've set the delegate for both the pickers to be self, both the pickers call the same methods.
To tell which picker is making the call, a couple of ways are:
Set a different tag value for each one when creating them and check the tag in the delegate method (eg. _pickerView1.tag = 1; and in the delegate method: if (pickerView.tag == 1)... )
Or, compare directly against the instance variable. For example:
- (void)pickerView:(UIPickerView *)pickerView //<-- std name as in doc
didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (pickerView == _pickerView1)
// Above:
// "pickerView" is the picker in which a row was selected
// "_pickerView1" is the actual instance variable
_pickerOutputLabel1.text = [nrArray objectAtIndex:row];
else
_pickerOutputLabel2.text = [nrArray objectAtIndex:row];
}
Also, you have IBOutlet in front of the control declarations but then you create them programmatically. If you are using Interface Builder to create the controls, don't re-create them in code. If you're not using IB, remove the IBOutlet.
you can also use this:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if( [pickerView isEqual: picker ]){
firststr = [firstArray objectAtIndex:row];
}
if( [pickerView isEqual: pickerAnother ]){
secondstr = [secondArray objectAtIndex:row];
}
}