Handling Data Object in UITableViewCell - ios

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;
}

Related

TableViewCellDelegate isnt being called

I am trying to add item to basket in this files. I have custom table cell and linked it with IBOutlets in storyboard. Somehow debugger reaches the delegate method inside deletegating object, but doesnt go further to TableVC, where this method is conformed, and no logs are seen.
// SeatTableViewCell.h
#import <UIKit/UIKit.h>
#import "SeatTableViewCellDelegate.h"
#interface SeatTableViewCell : UITableViewCell
#property (nonatomic, assign) id<SeatTableViewCellDelegate> delegate;
#property (nonatomic, weak) IBOutlet UILabel *rowLabel;
#property (nonatomic, weak) IBOutlet UILabel *seatLabel;
#property (nonatomic, weak) IBOutlet UILabel *priceLabel;
#property (nonatomic, weak) IBOutlet UIImageView *addToBasketImageView;
#end
// SeatTableViewCell.m
#import "SeatTableViewCell.h"
#implementation SeatTableViewCell
#synthesize rowLabel, seatLabel, priceLabel, addToBasketImageView;
- (void)awakeFromNib {
[super awakeFromNib];
UITapGestureRecognizer *singleImageTap = [[UITapGestureRecognizer alloc] initWithTarget:
self action:#selector(addToBasketTapDetected:)];
singleImageTap.numberOfTapsRequired = 1;
[self.addToBasketImageView addGestureRecognizer:singleImageTap];
}
- (void)addToBasketTapDetected: (UIGestureRecognizer *)sender {
//HERE the debugger stops, after step into nothing happens
[self.delegate tableViewCell:self didSelectImageView:self.addToBasketImageView];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
// SeatTableViewCellDelegate.h
#protocol SeatTableViewCellDelegate <NSObject>
- (void)tableViewCell:(UITableViewCell *)cell didSelectImageView:(UIImageView *)imageView;
#end
// ChooseSeatTableViewController.h
#import <UIKit/UIKit.h>
#import "SeatGroup.h"
#import "SeatTableViewCellDelegate.h"
#interface ChooseSeatTableViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, SeatTableViewCellDelegate>
- (IBAction)onBackPressed:(id)sender;
- (IBAction)OnChooseSectorClicked:(id)sender;
-(void)reloadData:(SeatGroup *)selectedSeatGroup;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, strong) SeatGroup *seatGroup;
#property (nonatomic, strong) NSString* perfUUID;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableHeightConstraint;
#property (nonatomic, strong) NSMutableArray* seats;
#end
// ChooseSeatTableViewController.m
#import "ChooseSeatTableViewController.h"
#import "ConcertDescriptionViewController.h"
#import "SeatTableViewCell.h"
#interface ChooseSeatTableViewController ()
#property (nonatomic, strong) NSMutableArray *selectedIndexPathes;
#property (strong) Seat* currentSeat;
#end
#implementation ChooseSeatTableViewController
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int volume = self.seats.count;
return volume;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_currentSeat = [_seats objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"seatCell";
//todo try fix bug with dequing indexes
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
Seat *cur = [_seats objectAtIndex:indexPath.row];
_currentSeat = cur;
cell.rowLabel.text = cur.rowNum;
cell.seatLabel.text = cur.seatNum;
NSArray* piecesOfPrice = [cur.price componentsSeparatedByString: #","];
if (piecesOfPrice.count > 1) {
cur.price = [piecesOfPrice objectAtIndex:0];
}
NSMutableString *prm = [cur.price mutableCopy];
[prm appendString:#" p"];
cell.priceLabel.text = prm;
[cell.addToBasketImageView setUserInteractionEnabled:YES];
if ([self.selectedIndexPathes containsObject:indexPath]) {
//set basket selected
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"rectangle_21_copy_5" ofType:#"png"];
UIImage *priceBckgImg = [[UIImage alloc] initWithContentsOfFile:thePath];
cell.addToBasketImageView.image = priceBckgImg;
} else {
//set basket unselected
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"rectangle_21_copy_6" ofType:#"png"];
UIImage *priceBckgImg = [[UIImage alloc] initWithContentsOfFile:thePath];
cell.addToBasketImageView.image = priceBckgImg;
}
return cell;
}
- (void)tableViewCell:(UITableViewCell *)cell didSelectImageView:(UIImageView *)imageView {
//HERE the debugger doesnt reach
NSLog(#"Hi, debugger in didSelectImageView");
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
if (![self.selectedIndexPathes containsObject:indexPath]) {
[self.selectedIndexPathes addObject:indexPath];
}
NSString *thePath = [[NSBundle mainBundle] pathForResource:#"rectangle_21_copy_5" ofType:#"png"];
UIImage *priceBckgImg = [[UIImage alloc] initWithContentsOfFile:thePath];
[imageView setImage:priceBckgImg];
[self.tableView reloadData];
}
..
Why my protocol isn being called?
You have to set your view controller as delegate:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"seatCell";
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.delegate = self;
....
}
AlexInspired,
The only statement missing is in cellForRowAtIndexPath :)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"seatCell";
//todo try fix bug with dequing indexes
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
Seat *cur = [_seats objectAtIndex:indexPath.row];
_currentSeat = cur;
cell.rowLabel.text = cur.rowNum;
cell.seatLabel.text = cur.seatNum;
cell.delegate = self;
....
return cell;
}
You didn't set delegate for tableview cell.
Set delegate and enjoy :) your problem is solved.
cell.delegate = self
you forget to set delegate to self. so in cellForRowAtIndexPath set delegate to self like,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"seatCell";
//todo try fix bug with dequing indexes
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.delegate = self;
}
by this you are assigning current class object to cell class so you can able to call current class method from cell class.
:)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"seatCell";
//todo try fix bug with dequing indexes
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.delegate=self;
.
.
.
write following code in CellforRowAtIndexPath method it will help for you
NSString *cellDdentifier = #"seatCell";
SeatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.delegate = self

Need help setting up custom cell

I've never implemented a custom cell for a tableView before and am confused on how to proceed. I'm trying to make a personality test app where each question is represented in a cell of my tableView and underneath each question are several buttons that will act as a response to the corresponding question. I've managed to set up my cell with a textview for the question and several buttons with appropriate constraints so they won't move.
I also set the Cell style to custom in the attributes inspector.
Can someone help me with how to set up the textview with my question? I tried making a property of UITextView and linking it to TextView in the cell but then an error arose saying I wasn't allowed to populate a reoccurring cell with an IBOutlet.
Here is a screenshot of my storyboard. Let me know if you need to see anything else.
TestVC.h
#import <UIKit/UIKit.h>
#import "Questions.h"
#import "CustomCell.h"
#interface TestViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (strong, nonatomic) IBOutlet UITextView *instructions;
#property (weak, nonatomic) IBOutlet UIButton *results;
//#property (strong, nonatomic) IBOutlet *question;
#property (nonatomic, strong) Questions *survey;
-(IBAction)backPressed:(id)sender;
#end
TestViewController.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [survey.questions count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"QuestionCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
/*
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
*/
NSString *que = (NSString *)[survey.questions objectAtIndex:indexPath.row];
//UITextView *textView = (UITextView *)[cell viewWithTag: 100];
cell.textView = (UITextView *)[cell viewWithTag: 100];
cell.textView.text = que;
return cell;
}
CustomCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell
// Variables for questions and answers
#property (weak, nonatomic) IBOutlet UITextView *textView;
#property (weak, nonatomic) IBOutlet UIButton *strongAgree;
#property (weak, nonatomic) IBOutlet UIButton *agree;
#property (weak, nonatomic) IBOutlet UIButton *weakAgree;
#property (weak, nonatomic) IBOutlet UIButton *neutral;
#property (weak, nonatomic) IBOutlet UIButton *strongDisagree;
#property (weak, nonatomic) IBOutlet UIButton *disagree;
#property (weak, nonatomic) IBOutlet UIButton *weakDisagree;
#end
CustomCell.m
#import "CustomCell.h"
#interface CustomCell ()
#end
#implementation CustomCell
#synthesize textView;
#synthesize strongAgree;
#synthesize agree;
#synthesize weakAgree;
#synthesize neutral;
#synthesize strongDisagree;
#synthesize disagree;
#synthesize weakDisagree;
#end
Set a tag for the UITextView in the attributes inspector and get it by the viewWithTag Method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"QuestionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSString *que = (NSString *)[survey.questions objectAtIndex:indexPath.row];
UITextView *textView = (UITextView *)[cell viewWithTag:100];//Use your tag
textView.text = que;
return cell;
}
this should work for you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"QuestionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSString *que = (NSString *)[survey.questions objectAtIndex:indexPath.row];
cell.textLabel.text = que;
return cell;
}
From what I see here, you doesn't create a custom cell, just a normal UITableViewCell
You need to create a subclass of UITableViewCell. Call it CustomCell or whatever, then give it the IBoutlet properties that you created in your storybard.
For exemple, in CustomCell.h :
#property (weak, nonatomic) IBOutlet UITextView textView;
Then in the cellForRowAtIndexPath :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"QuestionCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
// EDIT
if (!cell)
{
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}//
NSString *que = (NSString *)[survey.questions objectAtIndex:indexPath.row];
cell.textview.text = que;
return cell;
}
Finally in you storyboard, select the cell you customized, and setup its class in the inspector as CustomCell.
NB : Your IBOutlet properties should always be weak properties.

Unexpected delay when presenting UITableViewController

I have a custom UITableViewCell in a UITableViewController, but when the Controller tries to dequeue the custom cell, it will take a long time (like 2000ms).
This line of code causes the problem
KidsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"kidsReuseIdentifier" forIndexPath:indexPath];
The KidsListTableViewCell is a custom cell, which includes couple of UIButtons, some UILabels to show the information. And two delegate methods. It shouldn't be that slow to render that view. By the way, all of the information in the custom cell is basically static.
The is the full code of the UITableViewController. I put the custom view and regular view in different sections and I don't think this causes the problem.
#import "KidDetailTableViewController.h"
#import "KidDetailHeaderTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "Helper.h"
#interface KidDetailTableViewController () <KidDetailHeaderCellDelegate>
#end
#implementation KidDetailTableViewController
{
KidDetailHeaderTableViewCell *headerCell;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:#"KidDetailHeader" bundle:nil] forCellReuseIdentifier:#"kidDetail"];
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"detailCell"];
self.tableView.showsVerticalScrollIndicator = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
switch (section) {
case 0:
return 1;
break;
default:
return 10;
break;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
if (!headerCell) {
headerCell = [tableView dequeueReusableCellWithIdentifier:#"kidDetail"];
headerCell.delegate = self;
// Keep the background color for the cell when select.
headerCell.selectionStyle = UITableViewCellSelectionStyleNone;
headerCell.nicknameLabel.text = _kidNeedsToShow.nickname;
NSString *kidFullName = [NSString stringWithFormat:#"%# %# %#", _kidNeedsToShow.firstName, _kidNeedsToShow.midName, _kidNeedsToShow.lastName];
kidFullName ? (headerCell.fullNameLabel.text = #"") : (headerCell.fullNameLabel.text = kidFullName);
// Set thumb image or use default
// if there isn't image, use default.
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:_kidNeedsToShow.photoURL resultBlock:^(ALAsset *asset) {
[headerCell.avatarImage setImage:[UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]]];
} failureBlock:nil];
return headerCell;
}
else return headerCell;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"detailCell" forIndexPath:indexPath];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
- (void)didClickLeftButton:(UIButton *)leftButton {
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
I tried to put dequeueReusableCellWithIdentifier into a different thread, apparently it wouldn't work.
UPDATE: KidDetailHeaderTableViewCell.m
- (void)awakeFromNib {
// Initialization code
[_avatarImage.layer setCornerRadius:_avatarImage.frame.size.width / 2];
[_avatarImage.layer setBorderColor:[UIColor whiteColor].CGColor];
[_avatarImage.layer setBorderWidth:1.0];
[_avatarImage setClipsToBounds:YES];
}
- (IBAction)leftButtonClicked:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:#selector(didClickLeftButton:)]) {
[self.delegate didClickLeftButton:sender];
}
}
- (IBAction)rightButtonClicked:(UIButton *)sender {
if (self.delegate && [self.delegate respondsToSelector:#selector(didClickRightButton:)]) {
[self.delegate didClickRightButton:sender];
}
}
KidDetailHeaderTableViewCell.h
#protocol KidDetailHeaderCellDelegate <NSObject>
#optional
- (void)didClickLeftButton:(UIButton *)leftButton;
- (void)didClickRightButton:(UIButton *)rightButton;
#end
#interface KidDetailHeaderTableViewCell : UITableViewCell
#property (weak) id<KidDetailHeaderCellDelegate> delegate;
#property (weak, nonatomic) IBOutlet UILabel *fullNameLabel;
#property (weak, nonatomic) IBOutlet UIImageView *avatarImage;
#property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
#property (weak, nonatomic) IBOutlet UILabel *ageText;
#property (weak, nonatomic) IBOutlet UILabel *ageLabel;
#property (weak, nonatomic) IBOutlet UILabel *momentsStatistics;
#property (weak, nonatomic) IBOutlet UILabel *momentsLabel;
#property (weak, nonatomic) IBOutlet UIButton *rightButton;
#property (weak, nonatomic) IBOutlet UIButton *leftButton;
#end
UPDATE 2:
screenshot of instrument
The code for set the height of the cell. I have two sections, the first section actually is only used for header, the height is 290.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 290;
}
else return 60;
}
One of my friend pointed out that problem was caused by the custom font (Yes! I used custom font in the custom view). I still not sure about why this causes the problem (the font named 'hero'), but hope this will help someone else.

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.

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

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];
}

Resources