NSTableView add Button or Any Other custom object - objective-c

I Am trying to add Button programatically to NSTableView which is also defined programatically, no luck so far. My latest Code is:
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
auto dataRow = _tasks[row];
if([tableColumn.identifier isEqualToString:#"Id"]) {
NSTextField* text = [[NSTextField alloc] init];
text.stringValue = [NSString stringWithUTF8String:dataRow[0].c_str()];
return text;
} else if([tableColumn.identifier isEqualToString:#"Name"]) {
NSTextField* text = [[NSTextField alloc] init];
text.stringValue = [NSString stringWithUTF8String:dataRow[1].c_str()];
return text;
} else if([tableColumn.identifier isEqualToString:#"Check"]) {
NSTableCellView* cellView = [[NSTableCellView alloc] initWithFrame:NSMakeRect(0, 0, 200, 100)];
NSPopUpButtonCell* popupButtonCell = [[NSPopUpButtonCell alloc] init];
[popupButtonCell setPullsDown:YES];
[popupButtonCell insertItemWithTitle:#"dsadsa1" atIndex:0];
[popupButtonCell insertItemWithTitle:#"dsadsa2" atIndex:1];
NSPopUpButton* popupButton = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(0, 0, 200, 100) pullsDown:YES];
popupButton.cell = popupButtonCell;
[popupButton insertItemWithTitle:#"dsadsa" atIndex:0];
[popupButton insertItemWithTitle:#"dsadsa" atIndex:1];
NSTextField* text = [[NSTextField alloc] init];
NSTextFieldCell* textCell = [[NSTextFieldCell alloc] initTextCell:#"dsadsad"];
text.stringValue = [NSString stringWithUTF8String:"titleee"];
text.cell = textCell;
[cellView addSubview:text];
[cellView addSubview:popupButton];
return cellView;
}
the last column is showing empty for some reason

Related

UicollectionView didSelectItemAtIndexPath is not called in uiTableviewcell

I am working on chat view. For this I have used this code :Chat Code
This is working fine. Now I have used UIcollectionView in UItableViewCell. Collection view is working fine. But the issue is didselect method is not called of UICollectionView as well as UITableView. Please help me. I need your help very badly.
I have used this code in UITableViewCell Class:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.backgroundColor = [UIColor clearColor];
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0f) {
self.textLabel.backgroundColor = [UIColor whiteColor];
}
self.textLabel.font = [UIFont systemFontOfSize:14.0f];
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.textLabel.numberOfLines = 0;
self.textLabel.textAlignment = NSTextAlignmentLeft;
self.textLabel.textColor = [UIColor blackColor];
_timestampLabel = [[UILabel alloc] init];
_timestampLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_timestampLabel.textAlignment = NSTextAlignmentCenter;
_timestampLabel.backgroundColor = [UIColor clearColor];
_timestampLabel.font = [UIFont systemFontOfSize:12.0f];
_timestampLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
_timestampLabel.frame = CGRectMake(0.0f, 12, self.bounds.size.width, 18);
[self.contentView addSubview:_timestampLabel];
messageBackgroundView = [[UIImageView alloc] initWithFrame:self.textLabel.frame];
[self.contentView insertSubview:messageBackgroundView belowSubview:self.textLabel];
self.AvatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5,10+TOP_MARGIN, 50, 50)];
[self.contentView addSubview:self.AvatarImageView];
CALayer * l = [self.AvatarImageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:self.AvatarImageView.frame.size.width/2.0];
self.selectionStyle = UITableViewCellSelectionStyleNone;
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
[self.collectionView registerNib:[UINib nibWithNibName:#"ImageCollection" bundle:nil] forCellWithReuseIdentifier:#"Cell"];
[self.collectionView setUserInteractionEnabled:YES];
self.collectionView.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:self.collectionView];
[messageBackgroundView setUserInteractionEnabled:YES];
[self.contentView setUserInteractionEnabled:YES];
// UITapGestureRecognizer *lpgr // = [[UITapGestureRecognizer alloc] // initWithTarget:self action:#selector(tapRecognized:)]; // lpgr.numberOfTapsRequired
= 1; // lpgr.delegate = self; // [self.collectionView addGestureRecognizer:lpgr];
}
[self setUserInteractionEnabled:YES];
return self; }
In UIViewController I have used this code in tableView cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *L_CellIdentifier = #"SPHTextBubbleCell";
self.documentsArray = [[NSMutableArray alloc]init];
self.documentsArray = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Attachments"];
SPHTextBubbleCell *cell = [tableView dequeueReusableCellWithIdentifier:L_CellIdentifier];
cell.userInteractionEnabled = YES;
if (cell == nil)
{
cell = [[SPHTextBubbleCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:L_CellIdentifier];
}
// cell.bubbletype=(([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1))?#"LEFT":#"RIGHT";
if ([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1) {
cell.bubbletype = #"RIGHT";
}
else
{
cell.bubbletype = #"LEFT";
}
[cell setBackgroundColor:[UIColor clearColor]];
cell.textLabel.text = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Content"];
cell.textLabel.tag=indexPath.row;
NSString *dateString = [NSString stringWithFormat:#"%#",[self mfDateFromDotNetJSON:[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"UpdatedOn"]]];
NSLog(#"dateString..%#",dateString);
NSString *myString = [NSString stringWithFormat:#"%#",dateString];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss ZZZ";
NSDate *yourDate = [dateFormatter dateFromString:myString];
// NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
// [dateFormatter setTimeZone:utc];
dateFormatter.dateFormat = #"dd-MMM-yy HH:mm";
NSString *newString = [dateFormatter stringFromDate:yourDate];
NSLog(#"newString..%#",newString);
if ([self.documentsArray count]!=0)
{
cell.CustomDelegate = self;
[cell.collectionView setUserInteractionEnabled:YES];
[cell.collectionView setDelegate:self];
[cell.collectionView setDataSource:self];
cell.collectionView.delegate =self;
cell.collectionView.dataSource = self;
[cell.collectionView reloadData];
[cell.collectionView setHidden:NO];
[cell.collectionView setBackgroundColor:[UIColor clearColor]];
}
else
{
[cell.collectionView setHidden:YES];
}
cell.collectionView.tag =indexPath.row;
cell.timestampLabel.text = newString;
[cell.AvatarImageView sd_setImageWithURL:([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1)?[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"SellerPicture"] valueForKey:#"PictureUrl"]]]:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"BuyerPicture"] valueForKey:#"PictureUrl"]]]
placeholderImage:[UIImage imageNamed:#"Nav-profile1.png"]];
return cell;
}
Thanks in advance.
If your problem is that your UICollectionView taps do not cause the UITableViewCell it is in to be selected then you can bypass this by subclassing UICollectionView and modifying the hitTest function to your liking.
See my answer here.
This one lets you tap on anything outside of collection view items to select the table cell, but collection view items themselves will block the taps and process them as needed.
Modifying the hitTest method wasn't working in my case. I decided to use UITapGestureRecognizer.
// Custom UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(collectionViewTapped(_:)))
tapGR.numberOfTapsRequired = 1
self.collectionView.addGestureRecognizer(tapGR)
}
func collectionViewTapped(gr: UITapGestureRecognizer) {
let point = gr.locationInView(self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(point) {
// Do stuff
}
}
Don't forget to set delegate and dataSource.
self.tableView.delegate = self;
self.tableView.dataSource = self;

JSON data in table

(
{
"first_name" = Akash;
idprofile = 1;
iduser = 1;
"last_name" = Testing;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/1_Jellyfish.jpg";
"profile_picture_filepath" = "1_Jellyfish.jpg";
},
{
"first_name" = testing;
idprofile = 3;
iduser = 1;
"last_name" = tst;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/3_Penguins.jpg";
"profile_picture_filepath" = "3_Penguins.jpg";
},
{
"first_name" = test;
idprofile = 4;
iduser = 1;
"last_name" = test;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/4_Chrysanthemum.jpg";
"profile_picture_filepath" = "4_Chrysanthemum.jpg";
},
{
"first_name" = prashant1;
idprofile = 19;
iduser = 1;
"last_name" = kharade1;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/19_Koala.jpg";
"profile_picture_filepath" = "19_Koala.jpg";
},
{
"first_name" = Priyank;
idprofile = 68;
iduser = 1;
"last_name" = Jain;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/68_P.jpg";
"profile_picture_filepath" = "68_P.jpg";
},
{
"first_name" = sdasd;
idprofile = 106;
iduser = 1;
"last_name" = sdasd;
picUrl = "http://qalina.acapglobal.com/kangatime/ktapp/profilepics/1/";
"profile_picture_filepath" = "<null>";
}
)
this is my json response data. I want to display the six profiles(6 dictionaries) based on the "idprofile" key in a table view with first_name, last_name and the profile image. I am getting confused. Please help?
here's my code:
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *appDel = [[UIApplication sharedApplication]delegate];
navBar=[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
[navBar setTintColor:[UIColor colorWithRed:0.0f/255.0f green:82.0f/255.0f blue:151.0f/255.0f alpha:1.0f]];
UIImageView *myImageView=[[UIImageView alloc] initWithFrame:CGRectMake(87, 3, 134, 33)];
myImageView.image=[UIImage imageNamed:#"sprofile.png"];
[navBar addSubview:myImageView];
//[myImageView release];
[self.view addSubview:navBar];
UIButton *logOutButton=[UIButton buttonWithType:UIButtonTypeCustom] ;
[logOutButton setFrame:CGRectMake(244, 10, 71, 32)];
//[logOutButton setTitle:#"Log out" forState:UIControlStateNormal];
[logOutButton setImage:[UIImage imageNamed:#"logout.png"] forState:UIControlStateNormal];
[logOutButton addTarget:self action:#selector(goToLoginScreen) forControlEvents:UIControlEventTouchUpInside];
[navBar addSubview:logOutButton];
UILabel *headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 320, 30)];
[headerLabel setBackgroundColor:[UIColor colorWithRed:210.0f/255.0f green:221.0f/255.0f blue:228.0f/255.0f alpha:1.0f]];
[headerLabel setText:#"Currently selected profile: Please select"];
[headerLabel setTextAlignment:NSTextAlignmentCenter];
[headerLabel setFont:[UIFont fontWithName:#"helvetica" size:14.0f]];
[headerLabel setTextColor:[UIColor colorWithRed:78.0f/255.0f green:126.0f/255.0f blue:70.0f/255.0f alpha:1.0f]];
[self.view addSubview:headerLabel];
homeTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 81, 320, 367) style:UITableViewStylePlain];
[homeTable setBackgroundColor:[UIColor colorWithRed:232.0f/255.0f green:237.0f/255.0f blue:240.0f/255.0f alpha:1.0f]];
homeTable.delegate=self;
homeTable.dataSource=self;
homeTable.rowHeight=100;
[self.view addSubview:homeTable];
profileArray = [[NSMutableArray alloc]init];
[self callWebService];
}
-(void)goToLoginScreen
{
AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [profileArray 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];
}
UIButton *selectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
selectButton.frame = CGRectMake(100, 30, 63, 32);
//[selectButton setBackgroundColor:[UIColor yellowColor]];
[selectButton setBackgroundImage:[UIImage imageNamed:#"select.png"] forState:UIControlStateNormal];
//[selectButton addTarget:self action:#selector(selectButtonSelected: ) forControlEvents:UIControlEventTouchUpInside];
selectButton.tag = indexPath.row;
[cell.contentView addSubview:selectButton];
// NSDictionary *item = [profileArray objectAtIndex:[indexPath row]];
// [[cell textLabel] setText:[item objectForKey:#"first_name"]];
// Home *tempHomeObj=(Home *)[profileArray objectAtIndex:indexPath.row];
// NSString *fName = (NSString *)tempHomeObj.fName;
// NSLog(#"fnameeeee==>%#",fName);
//NSLog(#"fName==>%#",appDel.fName);
AppDelegate *appDel=(AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"profileeeee==>%#",profileArray);
// NSMutableString *tempStr = (NSMutableString *)profileArray;
cell.textLabel.text = [self.profileArray objectAtIndex:indexPath.row];
//cell.imageView.image = appDel.tempUserImage;
return cell;
}
-(void)callWebService
{
//adding the indicator view to show that data is being processed.......
indicatorView=[[UIView alloc] initWithFrame:CGRectMake(110 ,180,100 , 100)];
indicatorView.tag=3000;
[indicatorView setAlpha:0.7];
indicatorView.layer.cornerRadius=15;
indicatorView.backgroundColor=[UIColor blackColor];
[self.view addSubview:indicatorView];
//now adding the activity indicator
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//activityIndicator.frame = CGRectMake(20.0,20.0, 40.0, 40.0);
//activityIndicator.center = indicatorView.center;
activityIndicator.center=CGPointMake(50, 50);
[activityIndicator startAnimating];
[[self.view viewWithTag:3000]addSubview:activityIndicator];
// AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSURL *url = [NSURL URLWithString:#"http://qalina.acapglobal.com/kangatime/kangatime_api/api/user/all_profiles/format/json"];
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"1" forKey:#"id"];
//[request addPostValue:pwdField.text forKey:#"pass"];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
// NSLog(#"responsestring==%#",responseString);
NSMutableArray *responseArr= [responseString JSONValue];
NSLog(#"responseArr==>%#",responseArr);
NSDictionary *tempDict = [responseArr objectAtIndex:0];
//NSLog(#"tempDict==>%#",tempDict);
if(indicatorView!=nil)
{
[indicatorView removeFromSuperview];
indicatorView=nil;
}
for(NSDictionary *dict in tempDict)
{
Home *objHome=[[Home alloc] init];
AppDelegate *appDel = [[UIApplication sharedApplication]delegate];
appDel.fName = [tempDict objectForKey:#"first_name"];
NSLog(#"appDel.fName==>%#",appDel.fName );
appDel.lName = [tempDict objectForKey:#"last_name"];
//NSLog(#"lName==>%#",lName);
NSMutableString *myStr=[NSMutableString stringWithString:appDel.fName];
[myStr appendFormat:#" "];
[myStr appendString:appDel.lName];
objHome.userName=myStr;
NSLog(#"objHome.userName==>%#",objHome.userName);
NSString *idProfile = [tempDict objectForKey:#"idprofile"];
NSLog(#"idProfile==>%#",idProfile);
// NSString *imageStr=[tempDict objectForKey:#"profile_picture_filepath"];
// NSMutableString *urlString= [NSMutableString stringWithString:#"http://qalina.acapglobal.com/kangatime/ktapp/profilepics/"];
// [urlString appendString:imageStr];
// NSURL *mainURL=[[[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]] autorelease];
// // NSLog(#"mainURL==>%#",mainURL);
//
// appDel.tempUserData = [[NSData alloc] initWithContentsOfURL:mainURL];
//NSLog(#"tempUserData==>%#",tempUserData);
// Home *objHome=[[Home alloc] init];
//appDel.tempUserImage = [[UIImage alloc] initWithData:appDel.tempUserData];
[profileArray addObject:objHome.userName];
// [profileArray addObject:appDel.tempUserImage];
NSLog(#"profileArray==>%d",[profileArray count]);
}
//[profileArray addObject:]
// [homeTable setDataSource:self];
// [homeTable setDelegate:self];
[homeTable reloadData];
//[self setProfileArray:[tempDict objectForKey:#"first_name"]];
}
first you have parse the json. to parse the jason you can use JSONKit
With the help of JSONKIT, first you have to parse response string.
You will get array or dictionary from JSON response. #SmartWork has provided you a link for JSONKIT and How to create JSON Array string given below? will help you out to retrieve array/dictionary from response.

UIPickerView with a Done button in Ipad

I have faced one issue to display UIPickerView with a Done button in Ipad.
I done detailed researches though many links and blogs and got the suggestion as "display the UIPickerView from an UIActionSheet"
I saw many posts related this, however there is no good answers.So please dont close it as a duplicate.
Also i was able to get some good codes to do it and it worked fine in my Iphone devices.
However i were found a difficulty in Ipad devices.
The Action-Sheet is not displaying as a full view.
Please see the below screenshot.this was the result!!!
The code is used to do this is pasted below.
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:nil
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
[actionSheet addSubview:pickerView];
[pickerView release];
UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:#"Close"]];
closeButton.momentary = YES;
closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
closeButton.tintColor = [UIColor blackColor];
[closeButton addTarget:self action:#selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
[actionSheet addSubview:closeButton];
[closeButton release];
[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
[actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
Then I have downloaded a excellent sample application from github through sample pickers
After the download, i have copied the classes only mandatory for me to my application.
The method they are using to show the UIPickerView+Done button through Action-Sheet is described below
ActionStringDoneBlock done = ^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
if ([myLabel respondsToSelector:#selector(setText:)]) {
[myLabel performSelector:#selector(setText:) withObject:selectedValue];
}
};
ActionStringCancelBlock cancel = ^(ActionSheetStringPicker *picker) {
NSLog(#"Block Picker Canceled");
};
NSArray *colors = [NSArray arrayWithObjects:#"Red", #"Green", #"Blue", #"Orange", nil];//picker items to select
[ActionSheetStringPicker showPickerWithTitle:#"Select a Block" rows:colors initialSelection:0 doneBlock:done cancelBlock:cancel origin:myButton];
In the last line of code they have used the parameter as origin: and we can pass any objects (button,label etc) to it.
The Action-sheet will take origin as the passed object.
Here my issue came again :). I have used segment control to pick the time as per my conditions.
if i give mySegment as the origin parameter,the Action-sheet origin arrow will display from middle of my segment control.Not from the selected tab ,which is too bad and will give confusion to my valuable users.
So i have added individual labels under the segment sections and given it for the origin parameter of the mentioned method and i fixed my issue.
However i know its not a good fix :)
May i know is there any easy way to do it?
Is Apple support ActionSheet+UIPickerView+DoneButton in Ipad?
Any help on this issue is Appreciated
-(void)viewDidload
{
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.frame = CGRectMake(165,165, 135,35);
[button1 setTitle:#"Type #" forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(button1) forControlEvents:UIControlEventTouchUpInside];
[s addSubview:button1];
}
-(void)button1
{
items1 =[[NSMutableArray alloc]initWithObjects:#"H",#"E",#"T",#"K",nil];
myPickerView1 =[[UIPickerView alloc] initWithFrame:CGRectMake(60,80,200,300)];
myPickerView1.transform = CGAffineTransformMakeScale(0.75f, 0.75f);
myPickerView1.delegate = self;
myPickerView1.dataSource = self;
myPickerView1.showsSelectionIndicator = YES;
myPickerView1.backgroundColor = [UIColor clearColor];
myPickerView1.tag=1;
[myPickerView1 selectRow:1 inComponent:0 animated:YES];
[self.view addSubview:myPickerView1];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
switch (pickerView.tag)
{
case 1:
return [items1 count];
break;
case 2:
return [items2 count];
break;
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
switch (pickerView.tag)
{
case 1:
return[items1 objectAtIndex:row];
break;
case 2:
return[items2 objectAtIndex:row];
break;
}
return 0;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
switch (pickerView.tag)
{
case 1:
{
[button1 setTitle:[items1 objectAtIndex:row] forState:UIControlStateNormal];
}
break;
case 2:
{
[button2 setTitle:[items2 objectAtIndex:row] forState:UIControlStateNormal];
}break;
}
pickerView.hidden = YES;
}
You have to use UIPopOverController.
First, create a UIPickerViewController for iPhone. You need it for the nib, which will be pushed into the popOver. Initialize the picker in ViewWithPicker
.h
#import <UIKit/UIKit.h>
#class ViewWithPickerController;
#protocol PopoverPickerDelegate
#required
- (void) viewWithPickerController:(ViewWithPickerController*) viewWithPickerController didSelectValue:(NSString*) value;
#end
#interface ViewWithPickerController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
IBOutlet UIPickerView *pickerView;
id<PopoverPickerDelegate> delegate;
NSMutableArray *array;
}
#property(nonatomic, retain) IBOutlet UIPickerView *pickerView;
#property(nonatomic, assign) id<PopoverPickerDelegate> delegate;
#end
.m, after you initialized the array in viewDidLoad, picker methods:
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)picker {
return 1;
}
// returns the number of rows in each component.
- (NSInteger)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(NSInteger)component {
return [array count];
}
//returns the string value for the current row
- (NSString *)pickerView:(UIPickerView *)picker titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [array objectAtIndex:row];
}
//handle selection of a row
- (void)pickerView:(UIPickerView *)picker didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *value = [pickerView.delegate pickerView:picker titleForRow:row forComponent:component];
//notify the delegate about selecting a value
if(delegate != nil)
[delegate viewWithPickerController:self didSelectValue:value];
}
Then, import the viewWithPicker into your main class, create a button and give it this action:
- (IBAction) showPickerPopupAction:(id) sender {
self.viewWithPickerController = [[[ViewWithPickerController alloc] initWithNibName:#"ViewWithPicker" bundle:[NSBundle mainBundle]] autorelease];
viewWithPickerController.contentSizeForViewInPopover =
CGSizeMake(viewWithPickerController.view.frame.size.width, viewWithPickerController.view.frame.size.height);
viewWithPickerController.delegate = self;
self.popoverController = [[[UIPopoverController alloc]
initWithContentViewController:viewWithPickerController] autorelease];
[self.popoverController presentPopoverFromRect:popoverButtonForPicker.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
popoverController.delegate = self;
}
And to select a specific value
- (void) viewWithPickerController:(ViewWithPickerController*) viewWithPickerController didSelectValue:(NSString*) value
{
yourLabel.text = [NSString stringWithFormat:#"%# ",value];
}
Use UIPopoverController for done button in picker, create a view controller class in which take a picker and add navigation cancel and done button.
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:nextViewController];
_datePickerPopover = [[UIPopoverController alloc] initWithContentViewController:navigationController];
nextViewController.datePickerPopover = _datePickerPopover;
_datePickerPopover.delegate=self;
[_datePickerPopover setPopoverContentSize:CGSizeMake(320, 453) animated:NO];
if (isSearchOpen) {
[_datePickerPopover presentPopoverFromRect:CGRectMake(btn.frame.origin.x+10+245, btn.frame.origin.y+100-scrollPointY, 44, 44) inView:self.splitViewController.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
}
else
{
[_datePickerPopover presentPopoverFromRect:CGRectMake(btn.frame.origin.x+10+245, btn.frame.origin.y+55, 44, 44) inView:self.splitViewController.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];//
}
Try out below code for UIPicker View in iPad
-(IBAction)tDriveBtnPressed:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
[df release];
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDone:)];
[barItems addObject:doneBtn];
[doneBtn release];
[pickerToolbar setItems:barItems animated:YES];
[barItems release];
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
CGRect pickerRect = datePicker.bounds;
datePicker.bounds = pickerRect;
UIViewController* popoverContent = [[UIViewController alloc] init];
UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 344)];
popoverView.backgroundColor = [UIColor whiteColor];
datePicker.frame = CGRectMake(0, 44, 320, 300);
[datePicker addTarget:self action:#selector(dateChange:) forControlEvents:UIControlEventValueChanged];
[popoverView addSubview:pickerToolbar];
[popoverView addSubview:datePicker];
popoverContent.view = popoverView;
//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 244);
//create a popover controller
popoverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
CGRect popoverRect = [self.view convertRect:[tDriveBtn frame]
fromView:[tDriveBtn superview]];
popoverRect.size.width = MIN(popoverRect.size.width, 100) ;
popoverRect.origin.x = popoverRect.origin.x;
// popoverRect.size.height = ;
[popoverController
presentPopoverFromRect:popoverRect
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
//release the popover content
[popoverView release];
[popoverContent release];
}
-(void)dateChange:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text= [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
[df release];
}
- (void)pickerDone:(id)sender
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
txtDate.text= [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
[df release];
if (popoverController != nil) {
[popoverController dismissPopoverAnimated:YES];
self.popoverController=nil;
}
}

how can i make a uitableview container to bounce within the view

ok, so this is pretty simple one, but i hope i could explain this clearly - i have a table view that i would like to inset into a container, and then have the table bounces when it reaches the top / bottom. So far, I was able to put my table in a container, but the container is fixed on the view, while the table inside the container bounces. Again, I am looking for a way to fix the table to the container, while having the container bouncing.
Here is what I was able to do, following the code:
What I want to accomplish is to have the black box bouncing rather than the table within it.
my ViewDidLoad in the view controller .m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//General View Setup
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"backgroundimage.png"]];
self.view.backgroundColor = background;
//Table View Data
listOfItems = [[NSMutableArray alloc] init];
NSArray *appleComputers = [NSArray arrayWithObjects:#"iPhone",#"iPod",#"MacBook",#"MacBook Pro",nil];
NSDictionary *appleComputersDict = [NSDictionary dictionaryWithObject:appleComputers forKey:#"Computers"];
NSArray *otherComputers = [NSArray arrayWithObjects:#"HP", #"Dell", #"Windows", #"Sony", #"Ivory", #"IBM", nil];
NSDictionary *otherComputersDict = [NSDictionary dictionaryWithObject:otherComputers forKey:#"Computers"];
[listOfItems addObject:appleComputersDict];
[listOfItems addObject:otherComputersDict];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 300);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[self.view addSubview:tblSimpleTable];
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
self.tblSimpleTable.tableHeaderView = containerView;
}
why don’t you use UIScrollView for that.
I had tested your code & done required changes. Hope you like it.
Code :
(this is your .h file)
#import <UIKit/UIKit.h>
#interface tableScrollViewController : UIViewController
<UITableViewDelegate,UITableViewDataSource, UIScrollViewDelegate> {
UITableView *tblSimpleTable;
NSMutableArray *listOfItems;
NSMutableArray *appleComputers,*otherComputers;
UIScrollView *scrollView;
}
#end
(this is your .m file)
- (void)viewDidLoad {
[super viewDidLoad];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor grayColor];
scrollView.contentSize = CGSizeMake(300, 800);
appleComputers = [[NSMutableArray alloc] init]; // I made it by my style
[appleComputers addObject: #"iPhone"];
[appleComputers addObject:#"iPod"];
[appleComputers addObject:#"MacBook"];
[appleComputers addObject:#"MacBook Pro"];
otherComputers = [[NSMutableArray alloc] init];
[otherComputers addObject: #"HP"];
[otherComputers addObject:#"Dell"];
[otherComputers addObject:#"Windows"];
[otherComputers addObject:#"Sony"];
[otherComputers addObject:#"Ivory"];
[otherComputers addObject:#"IBM"];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 600);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct
style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.scrollEnabled = NO;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[scrollView addSubview:tblSimpleTable];
self.view = scrollView;
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
tblSimpleTable.tableHeaderView = containerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section == 0)
return [appleComputers count];
else if(section == 1)
return [otherComputers count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.section == 0)
cell.text = [NSString stringWithFormat:#"%#“,
[appleComputers objectAtIndex:indexPath.row]];
else if(indexPath.section == 1)
cell.text = [NSString stringWithFormat:#"%#“,
[otherComputers objectAtIndex:indexPath.row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
// do whatever here
}

UITableView: Removing cells

Guys, i have a little issue here. Im doing a search to my UITableView. I search "iPhone", it returns to me one result. Its ok. iPhone just has one result. But when i search for iPad, that has two results, it gives me 2 results, but the first row stills displaying iphone info. The second display the iPad correct information.
When i click on search bar again to search another word, it gives me the two desired rows of ipad. But when i press the cancel button, it returns to the iPhone and iPad rows.
What im doing wrong?
Thanks
Cell and Table Methods:
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.listCod count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"SearchResult";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell =
[[[UITableViewCell alloc]
initWithFrame:CGRectMake(0, 0, 180, 200)
reuseIdentifier:MyIdentifier]
autorelease];
UIColor *bkgColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"SearchViewTableCellBackground.png"]];
UIView* backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];
backgroundView.backgroundColor = bkgColor;
cell.backgroundView = backgroundView;
// Foto do produto
UIView *teste = [[UIView alloc] init];
teste.frame = CGRectMake(5, 5, 100, 100);
teste.backgroundColor = [UIColor blueColor];
[cell addSubview:teste];
// Label de Marca
UILabel *marca = [[UILabel alloc] init];
marca.frame = CGRectMake(115, 10, 195, 25);
marca.backgroundColor = [UIColor clearColor];
marca.textColor = [UIColor grayColor];
NSString *marcaString = [self.listMarca objectAtIndex:indexPath.row];
marca.font = [UIFont systemFontOfSize:13.0];
marca.text = marcaString;
[cell addSubview:marca];
[marca release];
// Label do nome do produto
UILabel *nome = [[UILabel alloc] init];
nome.frame = CGRectMake(115, 30, 195, 25);
nome.backgroundColor = [UIColor clearColor];
nome.textColor = [[UIColor alloc] initWithRed:26.0 / 255 green:177.0 / 255 blue:240.0 / 255 alpha:1.0];
nome.font = [UIFont boldSystemFontOfSize:25.0];
NSString *noemString = [self.listName objectAtIndex:indexPath.row];
nome.text = noemString;
[cell addSubview:nome];
[nome release];
//Preco
UILabel *preco = [[UILabel alloc] init];
preco.frame = CGRectMake(115, 55, 195, 25);
preco.backgroundColor = [UIColor clearColor];
preco.textColor = [UIColor grayColor];
// Manda preco e parcela pra tratar
[self priceFormat:[self.listPreco objectAtIndex:indexPath.row] :[self.listParcela objectAtIndex:indexPath.row]];
preco.font = [UIFont boldSystemFontOfSize:20.0];
preco.text = self.precoFinal;
[cell addSubview:preco];
//Parcela
UILabel *parcelaLabel = [[UILabel alloc] init];
parcelaLabel.frame = CGRectMake(115, 73, 195, 25);
parcelaLabel.backgroundColor = [UIColor clearColor];
parcelaLabel.textColor = [UIColor grayColor];
parcelaLabel.font = [UIFont systemFontOfSize:13.0];
parcelaLabel.text = self.parcelamentoFinal;
[cell addSubview:parcelaLabel];
}
return cell;
}
And the search bar methods:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES animated:YES];
self.theTableView.allowsSelection = NO;
self.theTableView.scrollEnabled = NO;
[theTableView setRowHeight:110];
}
- (void)searchDisplayController:(UISearchDisplayController *)controller
willShowSearchResultsTableView:(UITableView *)tableView
{
[tableView setRowHeight:[[self theTableView] rowHeight]];
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.tableData removeAllObjects];
[self.theTableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searchBar.text=#"";
[searchBar setShowsCancelButton:NO animated:YES];
[searchBar resignFirstResponder];
self.theTableView.allowsSelection = YES;
self.theTableView.scrollEnabled = YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
return NO;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// Converte a String do campo de busca
NSString* buscaGet =
[searchBar.text stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
// Conecta com a URL
NSString *endereco = [[NSString alloc] initWithFormat:#"http://localhost/icomm/test.php?nome=%#", buscaGet];
// Lê o resultado
TBXML * tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:endereco]] retain];
TBXMLElement * rootXMLElement = tbxml.rootXMLElement;
TBXMLElement * item = [TBXML childElementNamed:#"produto" parentElement:rootXMLElement];
listCod = [[NSMutableArray alloc] init];
listMarca = [[NSMutableArray alloc] init];
listName = [[NSMutableArray alloc] init];
listPreco = [[NSMutableArray alloc] init];
listParcela = [[NSMutableArray alloc] init];
while (item) {
// Seta a id do produto
TBXMLElement * codigo = [TBXML childElementNamed:#"item" parentElement:item];
NSString * codProd = [TBXML textForElement:codigo];
[self.listCod addObject:codProd];
// Seta a marca do produto
TBXMLElement * marca = [TBXML childElementNamed:#"marca" parentElement:item];
NSString * marcaProd = [TBXML textForElement:marca];
[self.listMarca addObject:marcaProd];
// Seta o nome do produto
TBXMLElement * nome = [TBXML childElementNamed:#"nome" parentElement:item];
NSString * nomeProd = [TBXML textForElement:nome];
[self.listName addObject:nomeProd];
// Seta o preco do produto
TBXMLElement * preco = [TBXML childElementNamed:#"preco" parentElement:item];
NSString * precoProd = [TBXML textForElement:preco];
[self.listPreco addObject:precoProd];
// Seta o parcela do produto
TBXMLElement * parc = [TBXML childElementNamed:#"parcela" parentElement:item];
NSString * parcProd = [TBXML textForElement:parc];
[self.listParcela addObject:parcProd];
// Procura o proximo produto.
item = [TBXML nextSiblingNamed:#"produto" searchFromElement:item
];
}
NSLog(#"%#", self.listName);
[searchBar setShowsCancelButton:NO animated:YES];
[searchBar resignFirstResponder];
self.theTableView.allowsSelection = YES;
self.theTableView.scrollEnabled = YES;
//Remove tudo da table e recarrega
[[[self searchDisplayController] searchResultsTableView] performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
[tableData removeAllObjects];
[theTableView reloadData];
}
Thanks for all.
You are only setting your labels up inside the if (cell == nil) part of your code. This only gets called the first time a cell is created; after that the cell is dequeued for reuse and you don't create a new cell. If you want to dequeue your cells like that, you need to set the text (and any other property of the label that might change) outside of that if statement. In order to get references to your labels, you will need to use tags and viewWithTag:.
Or if you want to simplify things, don't dequeue your tableCells; though this could lead to performance issues if you have a lot of cells.