Cannot remove dynamic UIButton - objective-c

The UIButton is created under #implementation . I have to remove it after some functions but[button removeFromSuperview] doesn't work. How can I remove that?
#import "TabBar.h"
#import "CustomCell.h"
#interface TabBar ()
#end
#implementation TabBar
UILabel *title;
NSString *par;
UIButton *button;
NSMutableArray *backlist;
- (NSString *)documentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
}
-(void)tbl_info{
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:#"icd10.plist"];
self.dataList = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (NSInteger i=[self.dataList count]-1; i>=0;i--) {
NSDictionary *d = [self.dataList objectAtIndex:i];
par=[d objectForKey:#"PARENTID"];
if(![par isEqualToString:self.val])
[self.dataList removeObjectAtIndex:i];
}
}
- (IBAction)ara:(id)sender{
[self tbl_info];
[self.tViewTab reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.dataList count];
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *name= [[self.dataList objectAtIndex:indexPath.row] objectForKey:#"NAME"];
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize labelSize = [name sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height>=63)
labelSize.height=63;
return labelSize.height+1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellid";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = (CustomCell*)[[[NSBundle mainBundle]
loadNibNamed:#"CustomCell" owner:nil options:nil]
lastObject];
}
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
cell.nameLabel.text = [d objectForKey:#"NAME"];
cell.cityLabel.text = [d objectForKey:#"CODE"];
cell.indexPath = indexPath;
CGSize maxSize = CGSizeMake(320/2, MAXFLOAT);
CGSize nameSize = [cell.nameLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
if(nameSize.height>=63)
nameSize.height=63;
cell.nameLabel.frame =CGRectMake(80, 0, 234, nameSize.height);
cell.cityLabel.text = [d objectForKey:#"CODE"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *d = [self.dataList objectAtIndex:indexPath.row];
NSMutableDictionary *backprop = [[NSMutableDictionary alloc] init];
[backprop setObject:self.val forKey:#"id"];
[backprop setObject:title.text forKey:#"name"];
[backlist addObject:backprop];
//back button
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
//parent and title label
[title setText:[d objectForKey:#"NAME"]];
self.val=[d objectForKey:#"ID"];
[self tbl_info];
[self.tViewTab reloadData];
}
-(void)touchEvent:(id)sender{
[title setText:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ]];
self.val= [[backlist objectAtIndex:backlist.count-1] objectForKey:#"id"];
[backlist removeObjectAtIndex:backlist.count-1];
if(backlist.count>0)
[button setTitle:[[backlist objectAtIndex:backlist.count-1] objectForKey:#"name" ] forState:UIControlStateNormal];
else
[button removeFromSuperview];
[self tbl_info];
[self.tViewTab reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
backlist =[[NSMutableArray alloc]init];
self.val=#"0";
[self tbl_info];
[self.tViewTab reloadData];
title =[[UILabel alloc]initWithFrame:CGRectMake(79.0, 07.0, 162, 21)];
title.text = #"ICD10 Kod Grupları"; //etc...
[self.view addSubview:title];
[title release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}

In place of this :
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
Try this :
if (button != nil) {
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];
}
Or try this :
if (button != nil) {
[button removeFromSuperView];
[button release]; // dont write this in case of ARC
button = nil;
}
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:#selector(touchEvent:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:title.text forState:UIControlStateNormal];
button.frame = CGRectMake(02.0, 02.0, 71, 32);
[self.view addSubview:button];

Not a solution but a workaround:
Use
[sender removeFromSuperview];
or respectively, because sender is of type id and not UIView*:
[(UIButton*)sender removeFromSuperview];
But you could change sender to UIView* savely.
-(void)touchEvent:(UIView *)sender{
Some even put UIButton* in there. I personally don't like that but it is quite save if you know for sure that the message is sent by UIButtons only.
Another workaround would be to set the .tag property of the button and then fetch the real buttom from self.view by its tag.

Related

How to set delegate to UICollectionView in NSObject controller

How to add CollectionView in NSObject controller?
I have one NSObject controller which i am accessing on each ViewController. I already added some component on it like image view. Now I want to add CollectionView on it. I have written code as follows:
in AboutMe.h file
#interface AboutMe : NSObject<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
-(UIButton *) showAboutMeView:(UIViewController *)id;
#end
and in AboutMe.m file
#import "AboutMe.h"
#implementation AboutMe {
UIView *objMessageView;
UICollectionView *_collectionView
NSMutableArray *arrstrProfileImage;
NSMutableArray *arrstrUsersNameEn;
NSMutableArray *arrstrUsersNameMr;
}
-(UIButton *) showAboutMeView:(UIViewController *)id {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenX = screenRect.origin.x;
CGFloat screenY = screenRect.origin.y;
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
arrstrProfileImage = [[NSMutableArray alloc] initWithObjects:#"male.png",#"female.png",nil];
arrstrUsersNameEn = [[NSMutableArray alloc] initWithObjects:#"Mr. (Corporator)",#"Mrs.(Corporator)", nil];
objMessageView = [[UIView alloc] initWithFrame:CGRectMake(screenX, screenY, screenWidth,screenHeight-64)];
objMessageView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.8f];
[id.view addSubview:objMessageView];
UIImageView *objUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, screenWidth, 150)];
objUIImageView.image = [UIImage imageNamed:#"abc.png"];
objUIImageView.contentMode = UIViewContentModeScaleAspectFit;
[objMessageView addSubview:objUIImageView];
UIButton *objUIButtonOk = [[UIButton alloc] initWithFrame:CGRectMake(screenX, screenHeight-120, screenWidth, 50)];
[objUIButtonOk setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
objUIButtonOk.titleLabel.font = [UIFont boldSystemFontOfSize:25];
[objUIButtonOk setTitle:#"OK" forState:UIControlStateNormal];
[objMessageView addSubview:objUIButtonOk];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(objMessageView.frame.origin.x+10, objUIImageView.frame.origin.y+objUIImageView.frame.size.height+5, objMessageView.frame.size.width-20, objUIButtonOk.frame.origin.y-(objUIImageView.frame.origin.y+objUIImageView.frame.size.height+25)) collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
_collectionView.showsVerticalScrollIndicator = NO;
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor gray]];
[objMessageView addSubview:_collectionView];
return objUIButtonOk;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrstrProfileImage.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *objUIImageView;
UILabel *objUILabel;
for (UILabel *lbl in cell.contentView.subviews)
{
if ([lbl isKindOfClass:[UILabel class]])
{
[lbl removeFromSuperview];
}
}
for (UIImageView *img in cell.contentView.subviews)
{
if ([img isKindOfClass:[UIImageView class]])
{
[img removeFromSuperview];
}
}
cell.backgroundColor=[UIColor lightGrayColor];
cell.layer.cornerRadius = 3;
cell.layer.masksToBounds = YES;
objUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width/2-50, cell.contentView.frame.origin.y+25, 100, 100)];
objUIImageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",[arrstrProfileImage objectAtIndex:indexPath.row]]];
objUIImageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:objUIImageView];
objUILabel = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x+5, objUIImageView.frame.size.height+20, cell.contentView.frame.size.width-10, cell.contentView.frame.size.height - (objUIImageView.frame.size.height+20))];
objUILabel.backgroundColor = [UIColor clearColor];
objUILabel.textAlignment = NSTextAlignmentCenter;
objUILabel.numberOfLines = 0;
objUILabel.lineBreakMode = NSLineBreakByWordWrapping;
objUILabel.font = [UIFont boldSystemFontOfSize:16];
objUILabel.textColor = [UIColor blackColor];
if ([[NSString stringWithFormat:#"%#",[UserDefault objectForKey:#"lang"]] isEqualToString:#"M"]) {
objUILabel.text = [arrstrUsersNameMr objectAtIndex:indexPath.row];
}else{
objUILabel.text = [arrstrUsersNameEn objectAtIndex:indexPath.row];
}
[cell.contentView addSubview:objUILabel];
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(objMessageView.frame.size.width/2 -15,objMessageView.frame.size.width/2 -15);
}
#end
I am accessing this in ViewController as:
AboutMe *objAboutMe = [[AboutMe alloc] init];
UIButton *objBtn = [objAboutMe showAboutMeView:self];
[objBtn addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
A blank white view get loaded.
Here Problem is I am not able to set Delegate to CollectionView.
Please Help me in this.
You're CollectionView delegate won't work unless you change inheritation of your AboutMe class.
So you need to update this line and inherit from UIViewController:
#interface AboutMe : UICollectionViewController <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
Also I would make an additional suggestion. When working with method like this:
-(UIButton *) showAboutMeView:(UIViewController *)id {
Try to mantain only that code, that is related to creation and returning UIButton, so for example instantiation and operations with objMessageView could be placed in another method, etc.

how to maintain state of uibutton in table view

I have a table view in that I am using a custom cell. I have two buttons on each table view cell named "edit" and "cancel" both have images in cellForRow. What I want that when user clicks on edit button at same time same rows cancel button should change its image. Code is Working but it not changing same rows cancel button image. Its changing another rows cancel button image. How to maintain state of each button.
Here Is Code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
simpleTableIdentifier = #"MenuNameCell";
MenuNameCell *cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell== nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
//Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton setTag:indexPath.row];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setTag:indexPath.row];
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
// Adding All To Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
//objc_setAssociatedObject(_checkButton, iindex, indexPath,OBJC_ASSOCIATION_RETAIN );
return cell;
}
-(void)editQuantity:(id)sender{
NSLog(#"count of the array is----%d",[imageViewArray count]);
button = (UIButton *)sender;
row = button.tag;
NSLog(#"---rowww%d",row);
_textFieldQuantity.userInteractionEnabled = YES;
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Try to make _cancelButton and _checkButton with different tag in the same cell, I think it is puzzle to make both of them with same tag in the same row.
Give different tag for each buttons first like :
[_checkButton setTag:indexPath.row];
[_cancelButton setTag:indexPath.row+100];
and in your editQuantity: method
button = (UIButton *)sender;
row = button.tag;
NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:row inSection:0];
UITableViewCell *newCell = [yourTable cellForRowAtIndexPath:currentIndexPath];
newCancelButton = (UIButton *)[newCell.contentView viewWithTag:row+100];
[newCancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
Do same in your cancelOreder: method to change image of _checkButton.
Also, use this for remove all subViews,
[cell.contentView.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
please try this solution
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CELL_ID"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CELL_ID"];
UIButton *_cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_cancelButton setFrame:CGRectMake(65, 13, 100, 28)];
[_cancelButton setTitle:#"Cancel" forState:UIControlStateNormal];
[_cancelButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
[_cancelButton setTag:1];
UIButton *_checkButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_checkButton setFrame:CGRectMake(200, 13, 100, 28)];
[_checkButton setTitle:#"Check" forState:UIControlStateNormal];
[_checkButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
[_checkButton setTag:2];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
}
return cell;
}
-(void) cancelOreder:(id)sender
{
UITableViewCell *cell = (UITableViewCell *)[(UIButton *)sender superview];
UIButton *btn = (UIButton *)[cell viewWithTag:2];
if(btn != nil)
{
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
-(void) editQuantity:(id)sender
{
UITableViewCell *cell = (UITableViewCell *)[(UIButton *)sender superview];
UIButton *btn = (UIButton *)[cell viewWithTag:1];
if(btn != nil)
{
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}
}
in this example i cheange text color of label you can change image,hope this will help you

how to show data to only visible tableview cells in ios

Hi guys i have a custom tableview cell with a scrollview in it.the problem is all the data is getting loaded in tableview cells at once.what i want is to load the data only for the visible cells in tableView.i used [indexPath forvisiblerows]; it was in vain..cud u guys help me out below is the code.
-(IPadTableViewCell *)getNewCell
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"IpadTableViewCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if ([currentObject isKindOfClass:[IPadTableViewCell class]])
{
cell= (IPadTableViewCell *)currentObject;
return cell;
}
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// static NSString *CellIdentifier = #"IpadTableViewCell";
//cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
id1=[NSString stringWithFormat:#"%i",indexPath.row];
cell=[dicAlbumCells objectForKey:id1];
if (cell == nil) {
cell=[self getNewCell];
}
cell.tag=indexPath.row;
return cell;
}
-(void)loadImagesForOnscreenRows
{
NSArray *visiblePaths = [tblGallery indexPathsForVisibleRows];
for (NSIndexPath *indexPath in visiblePaths) {
if (imageArray > 0) {
[self imageButtonClicked:nil];
}
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self loadImagesForOnscreenRows];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self loadImagesForOnscreenRows];
}
-(void)imageButtonClicked:(id)sender
{
CGFloat prevButtonXPosition = 18, pageButtonXPosition, pageButtonWidth = 144, pageButtonHeight = 143;
for (NSInteger i =0; i<9; i++) {
pageButtonXPosition = prevButtonXPosition ;
prevButtonXPosition = pageButtonXPosition+pageButtonWidth+20;
UIButton *pageButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pageButton setContentMode:UIViewContentModeScaleAspectFit];
pageButton.layer.borderColor=[[UIColor whiteColor]CGColor];
pageButton.layer.borderWidth = 3;
pageButton.layer.cornerRadius = 0;
[pageButton addTarget:self action:#selector(onClickImage:) forControlEvents:UIControlEventTouchUpInside];
[pageButton setFrame:CGRectMake(pageButtonXPosition,0, pageButtonWidth, pageButtonHeight)];
[pageButton setBackgroundImage:[UIImage imageNamed:[imageArray objectAtIndex:i]] forState:UIControlStateNormal];
[pageButton setTag:i];
[cell.scrollView addSubview:pageButton];
}
UIButton *add=[UIButton buttonWithType:UIButtonTypeCustom];
add.layer.borderColor=[[UIColor whiteColor]CGColor];
add.layer.borderWidth = 3;
add.layer.cornerRadius = 0;
[add addTarget:self action:#selector(onClickAdd:) forControlEvents:UIControlEventTouchUpInside];
[add setFrame:CGRectMake(prevButtonXPosition, 0, 144, 143)];
[add setBackgroundImage:[UIImage imageNamed:#"grey.png"] forState:UIControlStateNormal];
[add setTag:0];
[cell.scrollView addSubview:add];
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(prevButtonXPosition+35,30, 76,76)];
[iv setImage:[UIImage imageNamed:#"last.png"]];
[cell.scrollView addSubview:iv];
[cell.scrollView setContentSize:CGSizeMake(prevButtonXPosition +165, 40)];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell.contentView addSubview:cell.scrollView];
}

how to redirect to a new screen on the button click in the table view in objective c

I have created a table view and added some labels and displaying it, now i need a button in each cell, where on click on the button, it has redirect to the new screen.
The following is the code which i am trying to redirect,
- (void)viewDidLoad
{
vendorsArray = [CommonUserDetails sharedUserDetails].mVendorDictionary;
NSLog(#"vendorsArray is %# \n count is %d",vendorsArray,[vendorsArray count]);
loTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 43, 320, 400) style:UITableViewStylePlain];
[loTableView setBackgroundColor:[UIColor whiteColor]];
loTableView.delegate = self;
loTableView.dataSource = self;
loTableView.separatorColor = [UIColor grayColor];
[self.view addSubview:loTableView];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"myCell"];
if (cell == nil)
{
cell = [self tableviewCellWithReuseIdentifier:#"myCell"];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[self configureCell:cell forIndexPath:indexPath];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#define L1_TAG 1
#define L2_TAG 2
#define L3_TAG 3
#define L4_TAG 4
- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier
{
UITableViewCell* cell = [[UITableViewCell alloc]initWithFrame:CGRectMake(0, 0, 320, 100)reuseIdentifier:identifier];
UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 290, 30)];
[l1 setBackgroundColor:[UIColor clearColor]];
[l1 setFont:[UIFont systemFontOfSize:14]];
// [l1 setTextColor:[UIColor blackColor]];
l1.textColor = [UIColor colorWithRed:153/(CGFloat)255 green:51/(CGFloat)255 blue:0 alpha:1.0];
[l1 setAdjustsFontSizeToFitWidth:YES];
[l1 setTextAlignment:UITextAlignmentRight];
l1.tag = L1_TAG;
[cell.contentView addSubview:l1];
UILabel* l2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 20 , 300, 30)];
[l2 setBackgroundColor:[UIColor clearColor]];
l2.font = [UIFont boldSystemFontOfSize:14];
l2.textColor = [UIColor blackColor];
//l2.textColor = [UIColor colorWithRed:102/(CGFloat)255 green:102/(CGFloat)255 blue:153/(CGFloat)255 alpha:1.0];
l2.tag = L2_TAG;
[l2 setTextAlignment:UITextAlignmentLeft];
[cell.contentView addSubview:l2];
UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(5, 40, 190, 30)];
[l3 setBackgroundColor:[UIColor clearColor]];
[l3 setFont:[UIFont systemFontOfSize:14]];
[l3 setTextColor:[UIColor grayColor]];
// l3.textColor = [UIColor colorWithRed:102/(CGFloat)255 green:102/(CGFloat)255 blue:0/(CGFloat)255 alpha:1.0];
[l3 setAdjustsFontSizeToFitWidth:YES];
l3.tag = L3_TAG;
[cell.contentView addSubview:l3];
UILabel* l4 = [[UILabel alloc] initWithFrame:CGRectMake(5, 60, 190, 30)];
[l4 setBackgroundColor:[UIColor clearColor]];
[l4 setFont:[UIFont systemFontOfSize:14]];
[l4 setTextColor:[UIColor grayColor]];
//l4.textColor = [UIColor colorWithRed:0/(CGFloat)255 green:51/(CGFloat)255 blue:0/(CGFloat)255 alpha:1.0];
[l4 setAdjustsFontSizeToFitWidth:YES];
l4.tag = L4_TAG;
[cell.contentView addSubview:l4];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(150, 60, 70, 30);
[button setTitle:#"Pay" forState:UIControlStateNormal];
[cell.contentView addSubview:button];
[button addTarget:self action:#selector(payButton)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
UILabel *myl1 = (UILabel*)[cell viewWithTag:L1_TAG];
UILabel *myl2 = (UILabel*)[cell viewWithTag:L2_TAG];
UILabel *myl3 = (UILabel*)[cell viewWithTag:L3_TAG];
UILabel *myl4 = (UILabel*)[cell viewWithTag:L4_TAG];
NSDictionary *dictionary = [vendorsArray objectAtIndex:indexPath.row];
myl1.text= [NSString stringWithFormat:#"INo:%#",[dictionary objectForKey:#"iNo"]];
myl2.text=[dictionary objectForKey:#"vendorName"];
myl3.text= [NSString stringWithFormat:#"Amount:%#",[dictionary objectForKey:#"amount"]];
myl4.text= [NSString stringWithFormat:#"DDate:%#",[dictionary objectForKey:#"dDate"]];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
NSLog(#"count is %d",[vendorsArray count]);
return [vendorsArray count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #"Payables";
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
-(IBAction) payButton{
PayDescriptionController *mPayDescriptionController = [[PayDescriptionController alloc]initWithNibName:#"PayDescriptionController" bundle:nil];
mPayDescriptionController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.navigationController presentModalViewController:mPayDescriptionController animated:YES];
}
Where i am going wrong in the above code.
try this,
[self.navigationController pushViewController:mPayDescriptionController animated:YES];
see ,it is navigating to next view or not !! and if not then may be one of your object is null.

Issue With setting tag for Button UITableView

I have two buttons inside sectioned tableview cell thumbs up and thumbs down. Initially image of both button is not selected. When I select thumbs up button its image become thumbs up selected and other one become thumbsdown not selected and vice versa.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"mod:numberOfSectionsInTableView");
NSLog(#"[preferences count]=%d",[preferences count]);
return [preferences count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.choices count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexpath
{
NSLog(#"cellForRowAtIndexPath: DISPLAY TEST");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"Text is: %#", [choices objectAtIndex:indexpath.row]);
NSLog(#"CHOICE AT INDEX PATH IS: %#",[choices objectAtIndex:indexpath.row %[choices count]]);
cell.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
// Thumbs up button.
//UIButton *thumbsUp = [[UIButton alloc]init];
thumbsUp = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsUp setTag:(indexpath.row+(indexpath.section * 50))];
[thumbsUp addTarget:self action:#selector(thumbUp_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsUp setTitle:#"" forState:UIControlStateNormal];
thumbsUp.frame = CGRectMake(150.0, 20, 20, 15);
[thumbsUp setBackgroundImage:[UIImage imageNamed:#"thumbsup_not_selected.png"]
forState:UIControlStateNormal];
//NSLog(#"------------------>TAG TEST : %d",(indexpath.row+(indexpath.section * 50)));
[cell.contentView addSubview:thumbsUp];
// Thumbs down button
thumbsDown = [UIButton buttonWithType:UIButtonTypeCustom];
[thumbsDown addTarget:self action:#selector(thumbDown_ButtonClicked:event:)
forControlEvents:UIControlEventTouchUpInside];
[thumbsDown setTitle:#"" forState:UIControlStateNormal];
thumbsDown.frame = CGRectMake(200, 20, 20, 15);
[thumbsDown setTag:indexpath.row+120];
[cell.contentView addSubview:thumbsDown];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[thumbsDown setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]
forState:UIControlStateNormal];
}
NSLog(#"------------> TAG TEST %d",thumbsUp.tag);
cell.text = [choices objectAtIndex:(indexpath.row % [choices count])];
NSLog(#"HELLO FOR TESTING");
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
if (sectionTitle == nil) {
return nil;
}
// Create label with section title
UILabel *label = [[[UILabel alloc] init] autorelease];
label.frame = CGRectMake(15, 10, 300, 25);
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake(0.0, 1.0);
label.font = [UIFont boldSystemFontOfSize:16];
label.textAlignment = UITextAlignmentLeft;
label.text = sectionTitle;
// Create header view and add label as a subview
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(12, 0, 300, 60)];
[view autorelease];
[view addSubview:label];
//[view addSubview:segmentedControl];
view.backgroundColor = [UIColor grayColor];
return view;
}
//Thumbs Up Button Action
- (IBAction)thumbUp_ButtonClicked:(id)sender event:(id)event
{
NSLog(#"Thumbs Up Check!");
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *) [[button superview] superview];
NSIndexPath *indexPath = [myTable indexPathForCell:cell];
NSLog(#"indexpath =%d",indexPath.row);
//[button setTag:indexPath.row+(indexPath.section * 50)];
int cTag = [sender tag];
NSLog(#"------>TAG : %d", cTag);
NSLog(#"------> Calculated TAG %d",indexPath.row+(indexPath.section * 50));
if(cTag == (indexPath.row+(indexPath.section * 50)))
{
NSLog(#"BUTTON COUNT:");
[button setBackgroundImage:[UIImage imageNamed:#"thumbsup_selected.png"]
forState:UIControlStateNormal];
}
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
//int row = button.tag;
NSLog(#"SECTION IS:%d",section);
NSLog(#"ROW IS: %d",row);
NSArray *array = cell.contentView.subviews;
NSLog(#"NUMBER OF OBJECTS: %d",[array count]);
UIButton *test = (UIButton *)[array objectAtIndex:2];
[test setBackgroundImage:[UIImage imageNamed:#"thumbsdown_not_selected.png"]forState:UIControlStateNormal];
}
Due to issue with tag of button while I change image of one button several buttons are changing. If any one can please find a solution it will be helpful.... tag is setting for buttons in sections which we can view.
The reason is the bad use of the recycling/reuse mechanism (as with 75% of questions about UITableView…)
Go read the Table View Programming Guide in Apple's doc (and search SO and the web for any question related to tableview and the reuse mechanism)
Corrected the issue by creating buttons outside and inside if(cell == nil). Also created a mutable dictionary to keep the current state of the button.....