How to getlcell.label.text value of uitableview cell in a string - uitableview

I am making an app in which i am using tableview and in each table cell i am using checkboxes. now i am stuck in this place that when checkbox is checked i want to get value of that table-cell. like i am showing messages id in table cell i want to get messages_Id of that cells whose checkboxes are checked. means if select 1 checkbox its message id is store in NSString and if i select 2 checkboxes then 2 messages of these checkboxes are store in string how it can be done.below is my sample code of tableview and check boxes action
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *tableviewidentifier = #"cell";
__block tablecellTableViewCell *cell= [self.activitiesTableView_ dequeueReusableCellWithIdentifier:tableviewidentifier];
if(cell==nil)
{
cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableviewidentifier];
}if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1){
}
__block NSString *row = [NSString stringWithFormat:#"%ld",(long)indexPath.row];
cell.titlename.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"offerTitle"];
tocity.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"toCity"];
fromcity.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"fromCity"];
date.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageDate"];
time.text=[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageTime"];
[cell.button setBackgroundImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
[cell.button setImage:nil forState:UIControlStateNormal];
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]])
{
[cell.button setImage:[UIImage imageNamed:#"tick.png"]// here i am setting image
forState:UIControlStateNormal];
cell.contentView.backgroundColor=[UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
}
else
{
cell.backgroundColor=[UIColor clearColor];
}
cell.button.tag=indexPath.row;
[cell.button addTarget:self action:#selector(checkButton:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
and below is my check button code
-(IBAction)checkButton:(UIButton *)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tblvie];
NSIndexPath *indexPath = [self.tblvie indexPathForRowAtPoint:buttonPosition];
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]]) {
[self.checkimageArray removeObject:[self.lblArray objectAtIndex:indexPath.row]];
self.titleLabel.text=#"";
}
else {
[self.checkimageArray addObject:[self.lblArray objectAtIndex:indexPath.row]];
self.titleLabel.text=[NSString stringWithFormat:#"%ld selected",(long)sender.tag+1];
}
[self.tblvie reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade];
}
and i want to get value of these checked boxes in this button
- (IBAction)menubtun:(id)sender {
}

there if want the cell info of selected cell, just handle the action method of tickButton in custom cell it self not in controller use below code define a protocol and define a delegate see the below code
in tablecellTableViewCell.h
#import <UIKit/UIKit.h>
#class tablecellTableViewCell;
#protocol CustomCellDelegate <NSObject>
- (void)checkBoxButtonSelected:(tablecellTableViewCell *)cell; //this is the custom delegate method
#end
#interface tablecellTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIImageView *profileImageView; //i changed the name for conventions
#property (weak, nonatomic) IBOutlet UIButton *tickButton;
#property (weak, nonatomic) IBOutlet UILabel *nameLabel; //valuedate
#property (weak, nonatomic) IBOutlet UILabel *messageLabel;
#property (weak, nonatomic) IBOutlet UILabel *dateLabel;
#property (weak, nonatomic) IBOutlet UILabel *timeLabel;
#property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicatorView;
#property (weak, nonatomic) id<CustomCellDelegate> cellDelegate; //decleare a delegate hear
- (void)setFont:(UIFont *)font withString:(NSString *)title;
#end
and in tablecellTableViewCell.m all code is same but u have to connect a action to tickButton for example
#import "tablecellTableViewCell.h"
#implementation tablecellTableViewCell
//#synthesize button,image;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
[super awakeFromNib];
[self setUp];
}
//...same code of yours no need to change just a action method of tick button is added extra
//in this call a delegate method by passing the entire cell itself
- (IBAction)checkButtonAction:(id)sender
{
if([self.cellDelegate respondsToSelector:#selector(checkBoxButtonSelected:)])
{
[self.cellDelegate checkBoxButtonSelected:self];//hear u are passing the enire cell to Fbinbox..controller
}
}
in the controller class .h file
//..same code just confirm to protocol
#interface inboxViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,CustomCellDelegate> //confirm to protocol
{
int checkBoxesCount;
}
in .m file
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
__block tablecellTableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:tableviewidentifier];
if(cell == nil)
{
cell = [[tablecellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableviewidentifier];
}
if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1)
{
}
__block NSString *row = [NSString stringWithFormat:#"%ld",(long)indexPath.row];
cell.activityIndicatorView.hidden = NO;
[cell.activityIndicatorView startAnimating];
if([[[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"messageRead"] intValue]==0)
{
cell.contentView.backgroundColor=[UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
}
else
{
cell.contentView.backgroundColor=[UIColor clearColor];
}
cell.messageLabel.text = [[self.inboxmessagesarray objectAtIndex:indexPath.row]objectForKey:#"toCity"];
cell.cellDelegate = self;//add this one line
//... rest same code but comment the action method of tick button
//..hear in the last
cell.tickButton.tag = indexPath.row;
// [cell.tickButton addTarget:self action:#selector(checkButton:) forControlEvents:UIControlEventTouchUpInside]; //comemnt this line this tickbutton action is in custom cell
}
//now define custom delegate method
- (void)checkBoxButtonSelected:(tablecellTableViewCell *)cell //in this cell contains every thing including message and all
{
//hear u are getting the entire cell
//now u can get the all info stored in this cell
NSIndexPath *indexPath = [self.activitiesTableView_ indexPathForCell:cell];
if ([self.checkimageArray containsObject:[self.lblArray objectAtIndex:indexPath.row]]) {
[self.checkimageArray removeObject:[self.lblArray objectAtIndex:indexPath.row]];
//....other stuff's
//cell.textLabel.text;
//..all info present in the cell
}
else
{
[self.checkimageArray addObject:[self.lblArray objectAtIndex:indexPath.row]];
//..do other stuff
NSString *selectedMessage = cell.messageLabel.text;
//cell.textLabel.text;
//..all info present in the cell
NSLog(#"SELECTED MESSAGE->%#",selectedMessage);
}
[self.activitiesTableView_ reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation: UITableViewRowAnimationFade];
}

Related

How to get UITextfield value from custom UItableViewCell. If UITableviewCell have multiple UITextFields without using tag property

I have custom UITableViewCell (dynamically created) for Billing address and Shipping address .I want to get UITextField value .How I can get its value without using tag property.Following is screen of my UITableViewCell-
cellForRowAtIndexPath code is as-
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(isShippingShow){
switch (indexPath.section){
case 0:
{
CardListCell *cell = (CardListCell*)[tableView dequeueReusableCellWithIdentifier:#"CardListCell" forIndexPath:indexPath];
return cell;
}
break;
case 1:
{
NewCardCell *cell = (NewCardCell*)[tableView dequeueReusableCellWithIdentifier:#"NewCardCell" forIndexPath:indexPath];
return cell;
}
break;
case 2:
case 3:
{
PayAddressCell *cell = (PayAddressCell*)[tableView dequeueReusableCellWithIdentifier:#"PayAddressCell" forIndexPath:indexPath];
cell.txtCountry.delegate = self;
cell.txtCountry.inputView = _pickerView;
[self setTextFieldAccessoryView:cell.txtCountry];
return cell;
}
break;
case 4:
{
SettingCell *cell = (SettingCell*)[tableView dequeueReusableCellWithIdentifier:#"SettingCell" forIndexPath:indexPath];
[cell.swSetting addTarget:self action:#selector(changeState:) forControlEvents:UIControlEventValueChanged];
return cell;
}
break;
default:
break;
}
}
else{
switch (indexPath.section){
case 0:{
CardListCell *cell = (CardListCell*)[tableView dequeueReusableCellWithIdentifier:#"CardListCell" forIndexPath:indexPath];
return cell;
}
break;
case 1:{
NewCardCell *cell = (NewCardCell*)[tableView dequeueReusableCellWithIdentifier:#"NewCardCell" forIndexPath:indexPath];
return cell;
}
break;
case 2:
{
PayAddressCell *cell = (PayAddressCell*)[tableView dequeueReusableCellWithIdentifier:#"PayAddressCell" forIndexPath:indexPath];
cell.txtCountry.delegate = self;
cell.txtCountry.inputView = _pickerView;
[self setTextFieldAccessoryView:cell.txtCountry];
return cell;
}
break;
case 3:
{
SettingCell *cell = (SettingCell*)[tableView dequeueReusableCellWithIdentifier:#"SettingCell" forIndexPath:indexPath];
[cell.swSetting addTarget:self action:#selector(changeState:) forControlEvents:UIControlEventValueChanged];
return cell;
}
break;
default:
break;
}
}
return [UITableViewCell new];
}
Custom Cell class is as-
#import <UIKit/UIKit.h>
#interface NewCardCell : UITableViewCell
#property(nonatomic,weak) IBOutlet UITextField *txtCardHolderName;
#property(nonatomic,weak) IBOutlet UITextField *txtCardNumber;
#property(nonatomic,weak) IBOutlet UITextField *txtExpDate;
#property(nonatomic,weak) IBOutlet UITextField *txtCVV;
#end
#interface CardListCell : UITableViewCell
#property(nonatomic,weak) IBOutlet UILabel *lblCount;
#property(nonatomic,weak) IBOutlet UILabel *lblCardNumber;
#property(nonatomic,weak) IBOutlet UIImageView *imgCardIcon;
#property(nonatomic,weak) IBOutlet UIButton *btnSelectCard;
#end
#interface SettingCell : UITableViewCell
#property(nonatomic,weak) IBOutlet UILabel *lblCaption;
#property(nonatomic,weak) IBOutlet UISwitch *swSetting;
#end
#interface PayAddressCell : UITableViewCell
#property(nonatomic,weak) IBOutlet UITextField *txtAddress;
#property(nonatomic,weak) IBOutlet UITextField *txtCity;
#property(nonatomic,weak) IBOutlet UITextField *txtState;
#property(nonatomic,weak) IBOutlet UITextField *txtZipcode;
#property(nonatomic,weak) IBOutlet UITextField *txtCountry;
#end
You can track your value inside TextField's delegate textFieldDidEndEditing method :
NSString *strAddress; // in interface
-(void)textFieldDidEndEditing:(UITextField *)textField{
UITableViewCell *cell = (UITableViewCell *)textField.superview.superview; //track cell's view hierarchy
if (cell isKindOfClass:[PayAddressCell class]) {
PayAddressCell *settingCell = cell;
if (textField == cell.txtAddress) {
strAddress = textField.text; // your address textfield's value
}
// you can check all textfield as above .
}
}
You can use KVO to bind your textfield.text to your model data.
Create Cell Model class corresponding to each cell -
#interface CellModel : NSObject <NSCoding, NSCopying>
#property (nonatomic, strong) NSString *address;
#property (nonatomic, strong) NSString *city;
#property (nonatomic, strong) NSString *state;
#property (nonatomic, strong) NSString *zipcode;
#property (nonatomic, strong) NSString *country;
#end
In textfield Delegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
cellModel.address = textField.text;
// or cellModel.city = textField.text;
// or cellModel.state = textField.text;
// or cellModel.zipcode = textField.text;
// or cellModel.country = textField.text;
}
Do this in all tableView cell which you have created.

How to save button selection on UITableViewCell?

My app has a favourite button, on clicking it is converting into red heart and if I click againg then it is back to gray heart. Its working correct. But problem is reuseIdentifier,After scrolling, button just coming to original state because its resusing cell here.
How can I save selection of button so that they remain selected(if selected)
Code of tableViewCell class(.h file):
#import <UIKit/UIKit.h>
#interface favBTNTableViewCell : UITableViewCell
#property(nonatomic)UIButton *faVbtn;
#end
Code of tableViewCell class(.m file)
#import "favBTNTableViewCell.h"
#implementation favBTNTableViewCell
#synthesize faVbtn;
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier
{
self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
if(self)
{
faVbtn=[UIButton new];
[faVbtn setFrame:CGRectMake(10, 10, 25, 25)];
[faVbtn setBackgroundImage:[UIImage imageNamed:#"unsel"] forState:UIControlStateNormal];
[faVbtn addTarget:self action:#selector(clickOnfav) forControlEvents:UIControlEventTouchUpInside];
[faVbtn setSelected:YES];
[self.contentView addSubview:faVbtn];
}
return self;
}
-(void)clickOnfav
{
if ([faVbtn isSelected]) {
[faVbtn setBackgroundImage:[UIImage imageNamed:#"sel.jpg"] forState:UIControlStateNormal];
[faVbtn setSelected:NO];
}
else
{
[faVbtn setSelected:YES];
[faVbtn setBackgroundImage:[UIImage imageNamed:#"unsel"] forState:UIControlStateNormal];
}
}
Code of ViewContrller.m
#import "ViewController.h"
#import "favBTNTableViewCell.h"
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSString *ci;
}
#property (strong, nonatomic) IBOutlet UITableView *tv;
#end
#implementation ViewController
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 30;
}
-(UITableViewCell*)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
favBTNTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ci];
if(!cell)
{
cell=[[favBTNTableViewCell alloc]init];
cell.faVbtn.tag=indexPath.row;
}
return cell;
}
- (void)viewDidLoad {
_tv.delegate=self;
_tv.dataSource=self;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
You need corresponding data source for your cells. For this purpose you can, for example, create one more class and you will use it like an item for data source. Take a look:
#interface DataSourceItem : NSObject
#property (nonatomic, assign) BOOL isFavorite;
#end
#implementation DataSourceItem
#end
Then in view controller's code you need to populate array of data source items and manage your table view depending on this array:
#interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
NSString *ci;
}
#property (strong, nonatomic) IBOutlet UITableView *tv;
#property (strong, nonatomic) NSArray *dataSourceArray;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_tv.delegate=self;
_tv.dataSource=self;
NSMutableArray *temp = [NSMutableArray new];
// actually how many rows you table view need to have
for (NSUInteger i = 0; i < 30; i++)
{
[temp addObject:[DataSourceItem new]];
}
self.dataSourceArray = [temp copy];**
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// change dataSource item state
DataSourceItem *item = [self.dataSourceArray objectAtIndex:indexPath.row];
item.isFavorite = !item.isFavorite;
// change cell state
favBTNTableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
cell.faVbtn.selected = item.isFavorite;
}
-(NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataSource count];
}
-(UITableViewCell*)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
favBTNTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ci];
if(!cell)
{
cell=[[favBTNTableViewCell alloc]init];
cell.faVbtn.tag=indexPath.row;
}
// decision based on data source item state
cell.favBtn.selected = self.dataSource[indexPath.row];
return cell;
}
You can fix it like this:
Implement - (void)layoutSubviews method in your custom cell.
In - (void)layoutSubviews, check button state and then set the
right image on it:
->
- (void)layoutSubviews {
[super layoutSubviews];
UIImage *buttonImage = [faVbtn isSelected] ? [UIImage imageNamed:#"sel.jpg"] : [UIImage imageNamed:#"unsel"];
[faVbtn setBackgroundImage:buttonImage forState:UIControlStateNormal];
}
if you are using custom cell
register class/nib for your tableview in did load
[tblName registerNib:[UINib nibWithNibName:#"customCell" bundle:nil] forCellReuseIdentifier:#"customCell"];
henceforth in datasource method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell *cell =(customCell*) [tableView dequeueReusableCellWithIdentifier:#"customCell" forIndexPath:indexPath];
// your code here
return cell;
}
Do not forget to assign your cell identifier as "customCell" in cell attribute
Happy coding..
you can also check similar ans by me
Iphone: Checkmarks in UITableview get mixed up when scrolling

Handling Data Object in UITableViewCell

I would like to move everything in between the two lines into detailCell.m so that the only code in cellForRowAtIndexPath are the remaining three lines. What is the most effective way to do this? Thank you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DetailCell" forIndexPath:indexPath];
Job *aJob = self.jobs[indexPath.row];
_______________
[cell.titleLabel setText:aJob.title];
[cell.companyLabel setText:aJob.company];
if (aJob.logo != (NSString *)[NSNull null]) {
[cell.logoImageView setImageWithURL:[NSURL URLWithString:aJob.logo] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
else {
[cell.logoImageView setImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
_________________
return cell;
}
Here is DetailCell.h. DetailCell.m is currently empty.
#interface DetailCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *titleLabel;
#property (weak, nonatomic) IBOutlet UILabel *companyLabel;
#property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
#end
Create a method in DetailCell.h something like:
- (void)configureCell:(Job *)aJob atIndexPath:(NSIndexPath *)indexPath;
And implement it in DetailCell.m as you like it:
- (void)configureCell:(Job *)aJob atIndexPath:(NSIndexPath *)indexPath {
[self.titleLabel setText:aJob.title];
[self.companyLabel setText:aJob.company];
if (aJob.logo != (NSString *)[NSNull null]) {
[self.logoImageView setImageWithURL:[NSURL URLWithString:aJob.logo] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
} else {
[self.logoImageView setImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
}
That's about it... When you do that all you need to do in your cellForRowAtIndexPath method is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DetailCell" forIndexPath:indexPath];
Job *aJob = self.jobs[indexPath.row];
[cell configureCell:aJob atIndexPath: indexPath];
return cell;
}
You actually don't need indexPatin in that cell method, but i have a habit of passing it always to the cell as it's usually a good thing to have it available :)
DetailCell.h
#class Job;
#interface DetailCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *titleLabel;
#property (weak, nonatomic) IBOutlet UILabel *companyLabel;
#property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
-(void) setJobDetail:(Job*) aJob;
#end
In DetailCell.m add the following method with a import for Job.h.
-(void) setJobDetail:(Job*) aJob{
[self.titleLabel setText:aJob.title];
[self.companyLabel setText:aJob.company];
if (aJob.logo != (NSString *)[NSNull null]) {
[self.logoImageView setImageWithURL:[NSURL URLWithString:aJob.logo] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
else {
[self.logoImageView setImage:[UIImage imageNamed:#"placeholder.jpg"]];
}
}
After which your cellForRowAtIndex changes to.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DetailCell" forIndexPath:indexPath];
Job *aJob = self.jobs[indexPath.row];
[cell setJobDetail:aJob];
return cell;
}

Subclass of UITableView indexPath nil

I'm trying to subclass a UITableView. However, I'm unable to get an indexPath that isn't nil. The tableView has custom cells.
Here is my TouchTableView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h> //I brought this in because I'm saving audio files in my app
#import "SimpleTableCell.h"
#protocol myTableViewDelegate;
#interface TouchTableView : UITableView <UITableViewDelegate, UITableViewDataSource, AVAudioRecorderDelegate, AVAudioPlayerDelegate, UITextViewDelegate, UITextFieldDelegate, UIAlertViewDelegate>
#property (nonatomic, weak) id<myTableViewDelegate> myDelegate;
#property (strong, nonatomic) NSMutableArray *sortedFiles;
#property (strong, nonatomic) NSString *simpleTableIdentifier;
#property (strong, nonatomic) SimpleTableCell *cell;
#property BOOL inverted;
-(void)refreshTable;
#end
#protocol myTableViewDelegate <NSObject>
- (void)selectedFile:(TouchTableView *)tableView withURL: (NSURL *) tableViewURL IndexPath:(NSIndexPath *)indexPath;
-(void)didDelete:(TouchTableView *)tableView IndexPath:(NSIndexPath *)indexPath;
-(void)setSortedFile:(TouchTableView *)tableView;
#end
I attach a longpress like so:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//bring in your custom cell here
simpleTableIdentifier = #"SimpleTableCell";
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
[cell.textField setEnabled:NO];
//put in long press
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPress:)];
[longPressGesture setMinimumPressDuration:1.0];
[cell addGestureRecognizer:longPressGesture];
}
}
return cell;
}
Then I have the following method for when the longpress activates:
- (void)longPress:(UILongPressGestureRecognizer *)gesture
{
if (![cell.textField isEnabled]) {
// only when gesture was recognized, not when ended
if (gesture.state == UIGestureRecognizerStateBegan)
{
// get affected cell
cell = (SimpleTableCell *)[gesture view];
// get indexPath of cell
NSIndexPath *indexPath = [self indexPathForCell:cell];
[self selectRowAtIndexPath:indexPath animated:NO scrollPosition:0];
[cell.textField setEnabled:YES];
[cell.textField becomeFirstResponder];
}
}
}
In my viewController in viewDidLoad I have:
self.touchTableView = [[TouchTableView alloc] init];
[self.tableView setDelegate:self.touchTableView];
[self.tableView setDataSource:self.touchTableView];
self.touchTableView.myDelegate = self;
The problem is that the indexPath is always nil. You'll note that I'm calling self instead of self.tableView because self is the tableView. Is there a way to get the indexPath?
Sorry for the mess all. rmaddy was right. Ridiculous. The solution:
in my ViewController.h I set up:
#property (weak, nonatomic) IBOutlet TouchTableView *tableView;
Then I changed the last code in my example to
[self.tableView setDelegate:self.tableView];
[self.tableView setDataSource:self.tableView];
self.tableView.myDelegate = self;
[self.tableView refreshTable];
Now I'm getting the index path.

UITableView contents changed after scrolling back

I have custom TableView dynamically populated with custom cells, each cell contains 2 buttons with images and 2 labels.
When scrolling my Table view and than scrolling back the buttons picures are changed. This is my code for custom cell
.h file
class #interface CatalogCategoriesDetailsCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UIButton * firstStickerImageButton;
#property (nonatomic, weak) IBOutlet UIButton *secondStickerImageButton;
#property (strong, nonatomic) IBOutlet UILabel * firstStickerName;
#property (strong, nonatomic) IBOutlet UILabel * secondStickerName;
#end
.m file
#implementation CatalogCategoriesDetailsCell
#synthesize firstStickerImageButton = _firstStickerImageButton;
#synthesize secondStickerImageButton = _secondStickerImageButton;
#synthesize firstStickerName = _firstStickerName;
#synthesize secondStickerName = _secondStickerName;
#end
My TableViewControllerClass
.h file
#import "CatalogCategoriesStickerDetails.h"
#interface CatalogCategoriesDetails : UITableViewController
{
TagSingleton *sobj;
}
#property (strong,nonatomic) NSArray *categoryDetails;
#property (strong,nonatomic) NSString *selectedCategoryId;
#property (strong,nonatomic) NSMutableArray *categoryFileNames;
#property (strong, nonatomic) NSString *documentsDirectory;
#end
.m file
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.categoryFileNames count] / 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"categoryDetailsTableCell";
CatalogCategoriesDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CatalogCategoriesDetailsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSString *stickerFilePath = [self.documentsDirectory stringByAppendingString:#"/"];
//first column
if(self.stickerIndex < [self.categoryFileNames count])
{
NSString *stickerFileName = [self.categoryFileNames objectAtIndex:self.stickerIndex];
//NSLog(#"file name is %#", stickerFileName);
if(stickerFileName != #"end")
{
NSString *stickerFullFilePath = [stickerFilePath stringByAppendingString:stickerFileName];
UIImage *Image = [UIImage imageWithContentsOfFile:stickerFullFilePath];
[cell.firstStickerImageButton setImage:Image forState:UIControlStateNormal];
[cell.firstStickerImageButton setTag:self.stickerIndex];
[cell.firstStickerImageButton addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
NSLog(#"Tag is: %i",cell.firstStickerImageButton.tag);
//NSLog(#"filename is: %#",stickerFileName);
NSArray *stickerFileNameCoponents = [stickerFileName componentsSeparatedByString:#"_"];
NSString *stickerName = [stickerFileNameCoponents objectAtIndex: 1];
cell.firstStickerName.text = [cell.firstStickerName.text stringByAppendingString:stickerName];
}
}
//second column
if(self.stickerIndex < [self.categoryFileNames count] - 1)
{
NSString *stickerFileName = [self.categoryFileNames objectAtIndex:self.stickerIndex + 1];
//NSLog(#"file name is %#", stickerFileName);
if(stickerFileName != #"end")
{
NSString *stickerFullFilePath = [stickerFilePath stringByAppendingString:stickerFileName];
UIImage *Image = [UIImage imageWithContentsOfFile:stickerFullFilePath];
[cell.secondStickerImageButton setImage:Image forState:UIControlStateNormal];
[cell.secondStickerImageButton setTag:self.stickerIndex + 1];
[cell.secondStickerImageButton addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
NSLog(#"Tag is: %i",cell.secondStickerImageButton.tag);
//NSLog(#"filename is: %#",stickerFileName);
NSArray *stickerFileNameCoponents = [stickerFileName componentsSeparatedByString:#"_"];
NSLog(#"Sticker file name is: %#", stickerFileNameCoponents);
NSString *stickerName = [stickerFileNameCoponents objectAtIndex: 1];
cell.secondStickerName.text = [cell.secondStickerName.text stringByAppendingString:stickerName];
}
else
{
[cell.secondStickerImageButton setHidden:TRUE];
[cell.secondStickerName setHidden:TRUE];
}
}
self.stickerIndex +=2;
return cell;
}
-(void)buttonTapped:(UIButton *)button
{
int tag = button.tag;
//NSLog(#"Tag is %i", tag);
sobj = [TagSingleton singleObj];
sobj.buttonTag = [[NSNumber alloc] initWithInteger:tag];
[self performSegueWithIdentifier: #"StickerImageSegue" sender: self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"StickerImageSegue"])
{
CatalogCategoriesStickerDetails *detailViewController = [segue destinationViewController];
detailViewController.stickerFileNames = self.categoryFileNames;
detailViewController.documentsDirectory = self.documentsDirectory;
}
}
I have solved the problem, the issue was that I was using my own indexing instead of connecting cells to [indexpath row].

Resources