This is weird, I know but my [UITableView reloadData] is not removing old cells, like this:
The mess you see happened after I clicked on the + button, came back and changed values again. plus button pushes the navigationController to an another controller, and after I came back with clicking on the back button and changed the value, this is what I see. How is it possible?? I used a custom view (subclassed from UIView), which I created as a UIStepper with a UILabel. Here is the codes, the controller.m, and the .h-.m files for the custom UIView.
controller.m
#interface ViewController ()
#property NSString *docsDir;
#property sqlite3 *DB;
#property NSArray *dirPaths;
#property NSString* databasePath;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property BOOL isCreatedBefore;
#property NSArray *theList;
#end
#implementation ViewController
#synthesize docsDir;
#synthesize DB;
#synthesize dirPaths;
#synthesize databasePath;
- (void)viewDidLoad
{
[super viewDidLoad];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: [NSString stringWithFormat:#"database.db"]]];
[self createDatabase];
self.theList = [self readAllEntries];
}
-(void) viewWillAppear:(BOOL)animated{
self.theList = [self readAllEntries];
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.theList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ SeriesObject * obj = [self.theList objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellocan"];
UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:1];
[nameLabel setText:obj.name];
CounterView *seasonCounter = [[CounterView alloc] initWithX:220 WithY:28 WithName:obj.name withCount:obj.session withCustomTag:indexPath.row];
seasonCounter.tag = 2;
CounterView *episodeCounter = [[CounterView alloc] initWithX:268 WithY:28 WithName:obj.name withCount:obj.episode withCustomTag:indexPath.row];
episodeCounter.tag = 4;
[cell.contentView addSubview:seasonCounter];
[cell.contentView addSubview:episodeCounter];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
SeriesObject *obj = [self.theList objectAtIndex:indexPath.row];
[self deleteEntryWithID:obj.idd];
self.theList = [self readAllEntries];
[self.tableView reloadData];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 88;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
______and more about reading from database or deleting; not about the view. (this is a very simple app, as a free time hobby; so I didn't spend time to follow MVC)
CounterView.h
#interface CounterView : UIView
#property NSString* name;
#property NSInteger count;
#property UILabel *label;
#property NSInteger customTag;
- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag;
#end
CounterView.m
#interface CounterView()
#property NSString *docsDir;
#property sqlite3 *DB;
#property NSArray *dirPaths;
#property NSString* databasePath;
#end
#implementation CounterView
#synthesize docsDir;
#synthesize DB;
#synthesize dirPaths;
#synthesize databasePath;
- (id)initWithX:(CGFloat)xPoint WithY:(CGFloat)yPoint WithName:(NSString*)newName withCount:(NSInteger)newCount withCustomTag:(NSInteger)newTag
{
self = [super initWithFrame:CGRectMake(xPoint, yPoint, 24, 52)];
if (self) {
self.customTag = newTag;
self.count = newCount;
self.name = newName;
UIButton *btnUp = [[UIButton alloc] initWithFrame:CGRectMake(3, 2, 18, 12)];
[btnUp setImage:[UIImage imageNamed:#"top.png"] forState:UIControlStateNormal];
[btnUp addTarget:self action:#selector(increaseValue) forControlEvents:UIControlEventTouchUpInside];
UIButton *btnDown = [[UIButton alloc] initWithFrame:CGRectMake(3, 38, 18, 12)];
[btnDown setImage:[UIImage imageNamed:#"bottom.png"] forState:UIControlStateNormal];
[btnDown addTarget:self action:#selector(decreaseValue) forControlEvents:UIControlEventTouchUpInside];
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 14, 24, 24)];
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
self.label.textAlignment = NSTextAlignmentCenter;
[self addSubview:btnUp];
[self addSubview:btnDown];
[self addSubview:self.label];
}
return self;
}
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{
}
-(void) increaseValue{
self.count++;
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
}
-(void) decreaseValue{
self.count--;
[self.label setText:[NSString stringWithFormat:#"%ld", (long)self.count]];
}
____and some more database codes too..
In your cellForRowAtIndexPath: you are adding a subview every time. Cells are reused by UITableView, so when you reload you're getting a "dirty" cell. You need to check if the view is already there. If so, modify the view instead of adding one. Google "UITableViewCell viewWithTag" to see some sample code.
- (void)prepareForReuse
{
//remove your subviews here
[self.subViewToRemove removeFromSuperView];
}
I would recommend that you create a custom cell class derived from UITableViewCell and have it include your custom CounterView instances. In this case you won't need to add the subviews each time in your cellForRowAtIndexPath (Which is causing the problem you're having), you can instead pass it whatever values it requires.
after some modifications, using this in the cellForRowAtIndexpath: method solved everything. Thanks everyone.
if (cell != nil)
{
NSArray* subviews = [cell.contentView subviews];
for (UIView* view in subviews)
{
[view removeFromSuperview];
}
}
Related
i am doing feedback form using UITableview in that using custom checkbox for selection.In a UITableviewcell i placed four static buttons for options like,Very
Good,Good,Average,Below Average.
What i want is,i want to select only one button checked in a row, if i select another button checked automatically previous selected button should be unchecked.
Example: In same row suppose if i select Very Good first again i selected Average , previous selected Very Good should be unchecked.
Check My code Below for reference:
This is in cellforrowatindexpath
[cell.R1_BTN setImage:[UIImage imageNamed:#"Touch_G.png"] forState:UIControlStateNormal];
[cell.R1_BTN addTarget:self action:#selector(BtnClicked:) forControlEvents:UIControlEventTouchUpInside];
cell.R1_BTN.tag=1;
Click event here..
-(void)BtnClicked:(id)sender
{
//Need Code Here..
}
updated code for reference..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [GNM count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [GNM objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([[NM objectAtIndex:section] isKindOfClass:[NSArray class]])
{
return [[NM objectAtIndex:section] count];
}
else
{
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
FeedBackFormTVC *cell = [FeedBack_TV dequeueReusableCellWithIdentifier:#"ListCell" forIndexPath:indexPath];
cell.FBName_LBL.text = [[NM objectAtIndex:indexPath.section] isKindOfClass:[NSArray class]]
? [[NM objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]
: [NM objectAtIndex:indexPath.section];
// below for assigning code action event..
....
....
...
}
I tried using Tags,but i didn't get what i want, pls help me.. thanks in Advance.
I think that you should use model to set for UITableViewCell. Your model's .h file like :
#import <Foundation/Foundation.h>
typedef enum : NSInteger {
UNKNOWN = 0,
VERY_GOOD = 1,
GOOD = 2,
AVERAGE = 3,
BELOW_AVERAGE = 4
}RangeMark;
#interface CellModel : NSObject
#property(nonatomic, assign) RangeMark range;
#end
.m file like:
#import "CellModel.h"
#implementation CellModel
#end
than you should init a table cell with .xib file looks like:
and its .h file like :
#import <UIKit/UIKit.h>
#import "CellModel.h"
#interface TableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *veryGoodButton;
#property (weak, nonatomic) IBOutlet UIButton *goodButton;
#property (weak, nonatomic) IBOutlet UIButton *averageButton;
#property (weak, nonatomic) IBOutlet UIButton *belowAverageButton;
- (void)setupCellWithModel:(CellModel*)model;
#end
its .m file like :
#import "TableViewCell.h"
#implementation TableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)setupCellWithModel:(CellModel *)model {
if(model.range == VERY_GOOD) {
self.veryGoodButton.backgroundColor = [UIColor greenColor];
}
else if(model.range == GOOD) {
self.goodButton.backgroundColor = [UIColor blueColor];
}
else if(model.range == AVERAGE) {
self.averageButton.backgroundColor = [UIColor yellowColor];
}
else if(model.range == BELOW_AVERAGE) {
self.belowAverageButton.backgroundColor = [UIColor redColor];
}
}
- (void)prepareForReuse {
[super prepareForReuse];
self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
self.goodButton.backgroundColor = [UIColor lightGrayColor];
self.averageButton.backgroundColor = [UIColor lightGrayColor];
self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}
#end
Finally your view controller .h file should look like :
#import <UIKit/UIKit.h>
#import "TableViewCell.h"
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
and .m file should look like :
#import "ViewController.h"
#interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
NSMutableArray<CellModel*> *modelList;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
modelList = [NSMutableArray<CellModel*> new];
for (int i=0; i<50; i++) {
CellModel *cellModel = [[CellModel alloc] init];
cellModel.range = UNKNOWN;
[modelList addObject:cellModel];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:#"TableViewCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
[cell setupCellWithModel:[modelList objectAtIndex:indexPath.row]];
cell.veryGoodButton.tag = indexPath.row;
cell.goodButton.tag = indexPath.row;
cell.averageButton.tag = indexPath.row;
cell.belowAverageButton.tag = indexPath.row;
[cell.veryGoodButton addTarget:self action:#selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];
[cell.goodButton addTarget:self action:#selector(good:) forControlEvents:UIControlEventTouchUpInside];
[cell.averageButton addTarget:self action:#selector(average:) forControlEvents:UIControlEventTouchUpInside];
[cell.belowAverageButton addTarget:self action:#selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];
return cell;
return nil;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return modelList.count;
}
- (void) veryGood:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = VERY_GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) good:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) average:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void) belowAverage:(UIButton*)sender {
[modelList objectAtIndex: sender.tag].range = BELOW_AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.tag inSection:0] withCellModel:[modelList objectAtIndex: sender.tag]];
}
- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell prepareForReuse];
[cell setupCellWithModel:cellModel];
}
#end
that s all :)
At the end app looks like :
yes this will be a solution for you, at least I hope like this :)
first of all create a custom button .h file like this :
#import <UIKit/UIKit.h>
#interface CustomButton : UIButton
#property (assign) NSInteger sectionTag;
#property (assign) NSInteger rowTag;
#end
custom button .m file like this :
#import "CustomButton.h"
#implementation CustomButton
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
#end
then I changed a few things in TableViewCell .h file like this :
#import <UIKit/UIKit.h>
#import "CellModel.h"
#import "CustomButton.h"
#interface TableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet CustomButton *veryGoodButton;
#property (weak, nonatomic) IBOutlet CustomButton *goodButton;
#property (weak, nonatomic) IBOutlet CustomButton *averageButton;
#property (weak, nonatomic) IBOutlet CustomButton *belowAverageButton;
#property (weak, nonatomic) IBOutlet UILabel *itemLabel;
- (void)setupCellWithModel:(CellModel*)model;
#end
TableViewCell .m file like this :
#import "TableViewCell.h"
#implementation TableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)setupCellWithModel:(CellModel *)model {
if(model.range == VERY_GOOD) {
self.veryGoodButton.backgroundColor = [UIColor greenColor];
}
else if(model.range == GOOD) {
self.goodButton.backgroundColor = [UIColor blueColor];
}
else if(model.range == AVERAGE) {
self.averageButton.backgroundColor = [UIColor yellowColor];
}
else if(model.range == BELOW_AVERAGE) {
self.belowAverageButton.backgroundColor = [UIColor redColor];
}
[self.itemLabel setText:model.itemText];
}
- (void)prepareForReuse {
[super prepareForReuse];
self.veryGoodButton.backgroundColor = [UIColor lightGrayColor];
self.goodButton.backgroundColor = [UIColor lightGrayColor];
self.averageButton.backgroundColor = [UIColor lightGrayColor];
self.belowAverageButton.backgroundColor = [UIColor lightGrayColor];
}
and its .xib like this :
on the other side, there is only one change on CellModel .h file like this :
#import <Foundation/Foundation.h>
typedef enum : NSInteger {
UNKNOWN = 0,
VERY_GOOD = 1,
GOOD = 2,
AVERAGE = 3,
BELOW_AVERAGE = 4
}RangeMark;
#interface CellModel : NSObject
#property(nonatomic, assign) RangeMark range;
#property(nonatomic, copy) NSString* itemText;
- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range;
#end
and its .m file like this :
#import "CellModel.h"
#implementation CellModel
- (id)initWith:(NSString*)itemText withRangeMark:(RangeMark)range {
self = [super init];
if(self) {
self.itemText = itemText;
self.range = range;
}
return self;
}
#end
finally view controller .h file same but .m like this :
#import "ViewController.h"
#interface ViewController () <UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *modelList;
NSMutableArray<NSString*> *sectionTitleList;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
sectionTitleList = [NSMutableArray<NSString*> new];
[sectionTitleList addObject:#"RESERVATION"];
[sectionTitleList addObject:#"FRONT DESK"];
[sectionTitleList addObject:#"CASHIER"];
[sectionTitleList addObject:#"HOUSE KEEPING"];
modelList = [[NSMutableArray alloc] initWithCapacity: 4];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Service Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Good Speed" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Confirmation Quality" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Quick Service in Reservetion" withRangeMark:UNKNOWN],nil] atIndex:0];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Check In" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Happy on Their Service" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Coutesey" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Quick Service at Check In" withRangeMark:UNKNOWN],nil] atIndex:1];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Front Office & Reception" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Overall Quality of Room" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Check" withRangeMark:UNKNOWN],[[CellModel alloc] initWith:#"Response Time" withRangeMark:UNKNOWN],nil] atIndex:2];
[modelList insertObject:[NSMutableArray arrayWithObjects:[[CellModel alloc] initWith:#"Room Decor" withRangeMark:UNKNOWN],nil] atIndex:3];
// [modelList addObject: [[CellModel alloc] initWith:#"Service Speed" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Good Speed" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Confirmation Quality" withRangeMark:UNKNOWN]];
// [modelList addObject: [[CellModel alloc] initWith:#"Quick Service in Reservetion" withRangeMark:UNKNOWN]];
// for (int i=0; i<5; i++) {
// CellModel *cellModel = [[CellModel alloc] init];
// cellModel.range = UNKNOWN;
// cellModel.itemText = #"";
// [modelList addObject:cellModel];
// }
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:#"TableViewCell"];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSLog(#"section: %ld - row : %ld - item text : %#", (long)indexPath.section, (long)indexPath.row, ((CellModel*)[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]).itemText);
[cell setupCellWithModel:[[modelList objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
((CustomButton*)cell.veryGoodButton).rowTag = indexPath.row;
((CustomButton*)cell.veryGoodButton).sectionTag = indexPath.section;
((CustomButton*)cell.goodButton).rowTag = indexPath.row;
((CustomButton*)cell.goodButton).sectionTag = indexPath.section;
((CustomButton*)cell.averageButton).rowTag = indexPath.row;
((CustomButton*)cell.averageButton).sectionTag = indexPath.section;
((CustomButton*)cell.belowAverageButton).rowTag = indexPath.row;
((CustomButton*)cell.belowAverageButton).sectionTag = indexPath.section;
[cell.veryGoodButton addTarget:self action:#selector(veryGood:) forControlEvents:UIControlEventTouchUpInside];
[cell.goodButton addTarget:self action:#selector(good:) forControlEvents:UIControlEventTouchUpInside];
[cell.averageButton addTarget:self action:#selector(average:) forControlEvents:UIControlEventTouchUpInside];
[cell.belowAverageButton addTarget:self action:#selector(belowAverage:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[modelList objectAtIndex:section] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionTitleList.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
[label setFont:[UIFont boldSystemFontOfSize:12]];
[label setTextColor:[UIColor whiteColor]];
NSString *string =[sectionTitleList objectAtIndex:section];
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor darkGrayColor]];
return view;
}
- (void) veryGood:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = VERY_GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) good:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = GOOD;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) average:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void) belowAverage:(CustomButton*)sender {
((CellModel*)[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]).range = BELOW_AVERAGE;
[self setCellDynamicly:[NSIndexPath indexPathForRow:sender.rowTag inSection:sender.sectionTag] withCellModel:[[modelList objectAtIndex:sender.sectionTag] objectAtIndex:sender.rowTag]];
}
- (void)setCellDynamicly:(NSIndexPath*)indexPath withCellModel:(CellModel*)cellModel {
TableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell prepareForReuse];
[cell setupCellWithModel:cellModel];
}
#end
I think that it will work fine for you. Just do some change part of array init on code to dynamic :)
last appearance :
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 600;
self.tableView.rowHeight = UITableViewAutomaticDimension;
sectionTitleList = [NSMutableArray<NSString*> new];
for (NSString* sectionTitle in yourSectionResponseArray) {
[sectionTitleList addObject: sectionTitle];
}
modelList = [[NSMutableArray alloc] initWithCapacity: [sectionTitleList count]];
//your row title array has to be 2D array.
for(int i = 0; i < [sectionTitleList count]; i++) {
NSMutableArray* rowStringArray = [NSMutableArray new];
for(NSString* rowTitle in [your2DRowResponseArray objectAtIndex:i]) {
[rowStringArray addObject: rowTitle];
}
[modelList insertObject: rowStringArray];
}
}
May be this can help you.
Since you haven't provided us the API response details as requested earlier we are forced to use static value. Please replace sectionTitleList & modelList from the array API response. Please find the below code to be used to assign you API response to model created by #Gökhan Aydın .
sectionTitleList = #[#"RESERVATION",#"FRONT DESK",#"CASHIER",#"HOUSE KEEPING",#"COMMON"];
modelList = #[
#[
#"Service Speed",
#"Good Service",
#"Confirmation quality",
#"Quick Service in Reservation"
],
#[
#"Check In",
#"Happy on their Service",
#"Courtesey",
#"Quick Service at Checkin"
],
#[
#"Front office & reception",
#"Overall Quality of Room",
#"Check",
#"Response time"
],
#[
#"Room Decor",
#"Time taken to serveTime taken to serveTime taken t",
#"Bathroom",
#"Facilities in the Room",
#"Choice of menu",
#"Housekeeping",
#"Room Service"
],
#[
#"Overall Comments",
#"Will you come back again"
]
];
self.navigationItem.title = [modelList lastObject];
GNM = [sectionTitleList mutableCopy];
NM = [[NSMutableArray alloc]init];
for (NSArray *feedbacktitles in modelList) {
if ([feedbacktitles isKindOfClass:[NSArray class]]) {
__block NSMutableArray *tempArray = [NSMutableArray new];
[feedbacktitles enumerateObjectsUsingBlock:^(NSString *title, NSUInteger idx, BOOL * _Nonnull stop) {
FeedbackModel *model = [[FeedbackModel alloc]initWith:title withRangeMark:UNKNOWN];
[tempArray addObject:model];
if (idx == [feedbacktitles count] - 1 ) {
*stop = TRUE;
[self->NM addObject:tempArray];
tempArray = [NSMutableArray new];
}
}];
}
}
or by simple for loop
for (NSArray *feedbacktitles in modelList) {
NSLog(#"%#",feedbacktitles);
NSMutableArray* rowStringArray = [NSMutableArray new];
if ([feedbacktitles isKindOfClass:[NSArray class]]) {
for(int i = 0; i < [feedbacktitles count]; i++) {
NSString* rowTitle = [feedbacktitles objectAtIndex:i];
FeedbackModel *model = [[FeedbackModel alloc]initWith:rowTitle withRangeMark:UNKNOWN];
[rowStringArray addObject: model];
if (i == [feedbacktitles count] - 1) {
[NM addObject: rowStringArray];
rowStringArray = [NSMutableArray new];
}
}
}
}
I have two tableViewControllers, second tableViewController tableViewCell has textField and imageView, how can I get data from that textfield when I click navigationBarBackButton (I want to store that data in first tableViewController).
// code from second tableViewController...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cellID"];
cell.textLabel.text = #"SIM Name";
cell.detailTextLabel.text = #"AirTel";
cell.imageView.image = [UIImage imageNamed:#"Star2.png"];
return cell;
}
TableViewCell1 *cell1 = [tableView dequeueReusableCellWithIdentifier:#"cell1"];
cell1.nameTextField.delegate = self;
if (indexPath.row == 1) {
NSArray *cell1XibRef = [[NSBundle mainBundle]loadNibNamed:#"TableViewCell1" owner:self options:nil];
cell1 = [cell1XibRef objectAtIndex:0];
cell1.imageView.image = [UIImage imageNamed:#"Con.png"];
self.nameString = cell1.nameTextField.text;
return cell1;
}
return nil;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//Whenever people start editing your textfield
self.nameString = textField.text;
NSLog(#"%#", self.nameString);
}
So many ways to do that but I prefer this way
Save the textfield.text value in NSUserDefaults like this
[[NSUserDefaults standardUserDefaults] setObject:textField.text forKey:#"controllerTwo"];
And get that value in first controller
NSString *secondContrllerText = [[NSUserDefaults standardUserDefaults] stringForKey:#"controllerTwo"];
You can directly add cells in one array and loads cells from that array which will returns you latest cell with all your edits.
NSMutableArray *arrCells = [[NSMutableArray alloc] init];
for (init i=0; i<20; i++){
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"cellID"];
arrCells = cell;
}
In cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = arrCell[indexPath.row];
......
return cell;
}
here is the code i like to pass the data with block.here is the code wish to help you.
FirstViewController.h
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController
#end
FirstViewController.m
#import "FirstViewController.h"
#import "ViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)buttonClick
{
ViewController *controller = [[ViewController alloc] init];
controller.passTheTextFieldData = ^(NSString *textValue){
NSLog(#"show the %# textValue",textValue);
};
[self.navigationController pushViewController:controller animated:YES];
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) void (^passTheTextFieldData)();
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()<UITextFieldDelegate>
#property (nonatomic, strong) UITextField *textField;
#property (nonatomic, strong) NSString *textValue;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.textField addTarget:self action:#selector(textFieldValueChanged) forControlEvents:UIControlEventValueChanged];
}
- (void)textFieldValueChanged
{
self.textValue = self.textField.text;
}
- (void)navigationbarBackClick
{
if (self.passTheTextFieldData) {
self.passTheTextFieldData(self.textValue);
}
}
#end
Set the tag property for textField in tableViewCell
Then loop through the cells
for (int i = 0 ; i < [cellDataArray count] ; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
UITextField *txtfield = [[cell contentView]viewWithTag:2];
//now get the text txtfield.text
}
Hope this helps
Either you can use delegate method to store your value or use NSUserdefaults.But you have to store one value to pass it to another table view i recommend you to use NSUserdefaults.
//suppose you have to save text (get your data)
NSString *valueToSave = cell1.nameTextField.text;
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:#"keyAbcd"];
[[NSUserDefaults standardUserDefaults] synchronize];
//another page where you want to show your data (paste your data)
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"keyAbcd"];//your key have to be same
//print save value in nslog
When I click the UITableViewCell , It have selection effect (grey background in clicked cell),But didSelectRowAtIndexPath is not calling ,what happen?
EDIT
this is my code
tableView.h file
#interface PopCardView : MMPopupView <UITableViewDataSource, UITableViewDelegate>
#end
tableView.m file
#property (nonatomic, strong) NSMutableArray *tagsArray;
#property (nonatomic, strong) UIView *backView;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, assign) NSUInteger lastIndex;
#end
-(id)initWithTags:(NSMutableArray *)tags{
self = [super init];
if (self) {
self.backView = [[UIView alloc] init];
self.backView.backgroundColor = [UIColor whiteColor];
self.backView.layer.cornerRadius = 5;
self.backView.layer.masksToBounds = YES;
[self addSubview:self.backView];
[self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.bottom.right.equalTo(self);
}];
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 324, 300) style:UITableViewStylePlain];
_tableView.tableFooterView =[[UIView alloc] init];
[self.backView addSubview:_tableView];
[_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.right.bottom.equalTo(self.backView).insets(UIEdgeInsetsMake(45,0, 45, 15));
make.size.mas_equalTo(CGSizeMake(324, 200));
}];
[_tableView registerClass:[PopCardTagViewCell class] forCellReuseIdentifier:#"cell"];
_tableView.allowsSelection = YES;
_tableView.allowsSelectionDuringEditing = YES;
[_tableView setUserInteractionEnabled:YES];
_tableView.dataSource = self;
_tableView.delegate = self;
}
return self;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[_tagsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
PopCardData *data = (PopCardData *)obj;
data.selected = #"0";
if (idx == indexPath.row) {
data.selected = #"1";
}
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifer = #"cell";
PopCardTagViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifer];
if (!cell) {
cell = [[PopCardTagViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
}
[self configureCell:cell forIndexPath:indexPath];
return cell;
}
-(void)configureCell:(PopCardTagViewCell *)cell forIndexPath:(NSIndexPath *)indexPath {
PopCardData *data = (PopCardData *)[_tagsArray objectAtIndex:indexPath.row];
//configure cell
[cell setUserInteractionEnabled:YES];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _tagsArray.count;
}
EDIT2
this is my initialize code of PopCardView,it use swift
let pop = PopCardView(tags: self.m_model.getItmes())
pop.show()
The code you show does not set any delegate to the table view. Either this is the reason or you posted an incomplete code snippet.
self.tableView.delegate = self;
and add UITableViewDelegate to your interface like
#interface ClassName ()<UITableViewDelegate>
Make sure you don't have anything in the cell that can swallow the touch event. Things like buttons and textfields can cause this. Strip everything from your cell, test to see if it works, then add things back in slowly to find the culprit.
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
I have created a custom tableCell When I connect the xib via backgroundView to the file owner I successfully get items to appear in my table. The problem is I am not able to select a row and get a return.
If I unselect backgroundView then my custom cell does not populate but I am able to select a cell and extract a notification. I obviously want both of these items to work. Display my custom cell and have the ability to select a specific cell.
GameTableCell.m
#import "GameTableCell.h"
#implementation GameTableCell
#synthesize GameTime, AwayImage, HomeImage;
- (void)awakeFromNib {
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
/*
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
*/
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"GameTableCell" owner:self options:nil];
self = [topLevelObjects objectAtIndex:0];
return self;
}
#end
GameTable.h:
#import <UIKit/UIKit.h>
#interface GameTableCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *GameTime;
#property (weak, nonatomic) IBOutlet UIImageView *AwayImage;
#property (weak, nonatomic) IBOutlet UIImageView *HomeImage;
#end
HomePage.m:
#import "HomePage.h"
#import "PickSport.h"
#import "GameTableCell.h"
static NSString *CellIdentifier = #"GameTableCell";
NSString *headerText;
#interface HomePage ()
#end
#implementation HomePage
#synthesize ActiveChal,PendingChal;
-(IBAction)makeChallenge:(id)sender{
PickSport *second = [[PickSport alloc] initWithNibName:#"PickSport" bundle:nil];
[self presentViewController:second animated:YES completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Arrays for filling table cells
_HomeImages=#[#"ic_bengals_nfl",#"ic_bengals_nfl",#"ic_bengals_nfl",#"ic_bengals_nfl", ];
_AwayImages=#[#"ic_bears_nfl",#"ic_bears_nfl",#"ic_bears_nfl",#"ic_bears_nfl", ];
_SportGameInfo=#[#"7:00pm",#"8:00pm",#"9:00pm",#"10:00pm",];
[self.PendingChal registerClass:[GameTableCell class] forCellReuseIdentifier:CellIdentifier];
[self.ActiveChal registerClass:[GameTableCell class] forCellReuseIdentifier:CellIdentifier];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
//Set up the table props
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
//number of rows in the table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// rows eqiv to length of array SportGameinfo
return _SportGameInfo.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier=#"GameTableCell";
GameTableCell *cell = (GameTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//GameTableCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if(tableView == PendingChal){
NSLog(#"in Pend table");
int row =[indexPath row];
cell.HomeImage.image=[UIImage imageNamed:[_HomeImages objectAtIndex:indexPath.row]]; //thumbnails objectAtIndex:indexPath.row]
cell.AwayImage.image=[UIImage imageNamed:[_AwayImages objectAtIndex:indexPath.row]];
cell.GameTime.text=[_SportGameInfo objectAtIndex:indexPath.row];
}
if(tableView == ActiveChal){
NSLog(#"in Active table");
int row =[indexPath row];
cell.GameTime.text=_SportGameInfo[row];
cell.HomeImage.image=[UIImage imageNamed:_HomeImages[row]];
cell.AwayImage.image=[UIImage imageNamed:_AwayImages[row]];
}
return cell;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// 1. The view for the header
UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 22)];
if(tableView == PendingChal){
headerText= #"Pending Challenges (waiting on you)";
}
else {
headerText= #"Active Challenges";
}
// 2. Set a custom background color and a border
headerView.backgroundColor = [UIColor colorWithWhite:0.5f alpha:1.0f];
headerView.layer.borderColor = [UIColor colorWithWhite:0.5 alpha:1.0f].CGColor;
headerView.layer.borderWidth = 0;
// 3. Add a label
UILabel* headerLabel = [[UILabel alloc] init];
headerLabel.frame = CGRectMake(0, 0, tableView.frame.size.width -0, 20);
headerLabel.backgroundColor = [UIColor blackColor];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:16.0];
headerLabel.text = headerText;
headerLabel.textAlignment = NSTextAlignmentLeft;
// 4. Add the label to the header view
[headerView addSubview:headerLabel];
// 5. Finally return
return headerView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:[_SportGameInfo objectAtIndex:indexPath.row] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"willSelectRowAtIndexPath");
return indexPath;
}
#end
HomePage.h:
#import <UIKit/UIKit.h>
#interface HomePage : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *PendingChal;
#property (strong, nonatomic) IBOutlet UITableView *ActiveChal;
#property (nonatomic, strong)NSArray *HomeImages;
#property (nonatomic, strong)NSArray *AwayImages;
#property (nonatomic, strong)NSArray *SportGameInfo;
#end
And to be complete here are the connection of my HomePage.xib
Put aside your app's weird behavior I notice you are not rendering the table cell in the usual way. So first try to render it in usual way as this :
register nib in viewDidLoad because you create your cell in xib
- (void)viewDidLoad {
[super viewDidLoad];
// Arrays for filling table cells
_HomeImages=#[#"ic_bengals_nfl",#"ic_bengals_nfl",#"ic_bengals_nfl",#"ic_bengals_nfl", ];
_AwayImages=#[#"ic_bears_nfl",#"ic_bears_nfl",#"ic_bears_nfl",#"ic_bears_nfl", ];
_SportGameInfo=#[#"7:00pm",#"8:00pm",#"9:00pm",#"10:00pm",];
[self.PendingChal registerNib:[GameTableCell nib] forCellReuseIdentifier:CellIdentifier];
[self.ActiveChal registerNib:[GameTableCell nib] forCellReuseIdentifier:CellIdentifier];
}
dequeue reusable cell in - tableView:cellForRowAtIndexPath: and return it
you don't need load nib in tableViewCell's init method remove
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"GameTableCell" owner:self options:nil];
self = [topLevelObjects objectAtIndex:0];