I'm having a weird issue on UITableView delete action since iOS 11.
Here's the relevant TableView code :
#implementation ChatMessageListViewController(TableView)
#pragma mark - table view datasource/delegate
- (NSArray<UITableViewRowAction *> *) tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
NSMutableArray *rowActions = [NSMutableArray array];
UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:#"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[self deleteMessageAtIndexPath:indexPath];
}];
delete.backgroundColor = [UIColor redColor];
[rowActions addObject:delete];
return [rowActions copy];
}
- (void) deleteMessageAtIndexPath:(NSIndexPath *)indexPath {
NSString *threadID = [[self.messageArray objectAtIndex:indexPath.row] objectForKey:#"threadID"];
[self.tableView beginUpdates];
[self.messageArray removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
#weakify(self);
[UIUtil showLoadingHudWithText:WELocalString(#"message_remove_thread_loading_text", #"Deleting...", #"删除中...")];
[[AsyncUtil sharedInstance] dispatch_background_network:^{
DBManager *db = [[DBManager alloc] init];
[db deletetableData:[NSString stringWithFormat:#"singleChat WHERE threadID = '%#' ",threadID] ];
[[MemChatThreadMessages sharedInstance] removeThread:threadID];
NSDictionary * result = [Network deleteChatThread:threadID forEmail:[WEUtil getEmail]];
[[AsyncUtil sharedInstance] dispatch_main:^{
[UIUtil hideLoadingHuds];
#strongify(self);
if(self == nil) return ;
if([result[#"result"] isEqualToString:#"success"]){
}else{
[UIUtil showErrorMessage:WELocalString(#"message_remove_thread_error", #"Cannot delete this thread", #"不能删除该会话!")];
}
[self.tableView reloadData];
}];
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.messageArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if ([(NSString *)[messageInfo objectForKey:#"isAnnouncement"] isEqualToString:#"1"]) {
return 80;
}else if ([[messageInfo objectForKey:#"chatTag"] isValidString]){
return 80;
}else if([self isSpecialMessage:messageInfo]){
return 80;
}else{
return 67;
}
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"message";
if(self.events == nil){
NSDictionary * d = [WEUtil getMyEventListCache];
self.events = [[NSMutableDictionary alloc] init];
for(NSDictionary * eventSummary in d[#"events"]){
NSString * eventID = eventSummary[#"eventid"];
[self.events setObject:eventSummary forKey:eventID];
}
}
UserMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[UserMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
if(indexPath.row >= [self.messageArray count]){
TERMINATE_WITH_NIL_CELL;
}
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:messageInfo]){
[cell configureCellWithMessageDict:messageInfo];
}else{
[cell configureCellWithNewMessageDict:messageInfo withEvents:self.events];
}
return cell;
}
#pragma mark - Navigation
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:msgThreadDict]){
[self tableView:tableView didSelectNormalRowAtIndexPath:indexPath];
}else{
NSString * event = msgThreadDict[#"event"];
if([event isValidString]){
if([event isEqualToString:#"no_event_messages"]){
[UIUtil showErrorMessage:#"no event id"];
}else{
[BackendTracking trackingWithAction:#"open_special" withLabel:#"threads_list"];
SpecialTopicListViewController * special = [[SpecialTopicListViewController alloc] init];
special.tracking_src = #"tab";
[self.navigationController pushViewController:special animated:YES];
}
}
}
}
-(void) tableView:(UITableView *)tableView didSelectNormalRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
NSString *threadID = [msgThreadDict objectForKey:#"threadID"];
NSString *jid = [msgThreadDict objectForKey:#"jid"];
[GATracking trackCategory:#"message" withAction:#"thread_list_item_click" withLabel:threadID];
[[MemChatThreadMessages sharedInstance] setCurrentThreadID:threadID];
PrivateMessageViewController * chatVC = [[PrivateMessageViewController alloc] init];
chatVC.threadID = threadID;
chatVC.targetJID = jid;
chatVC.targetName = [msgThreadDict objectForKey:#"name"];
chatVC.unreadMsgNumber = [[self.messageArray objectAtIndex:indexPath.row][#"unreadCnt"] integerValue];
if ([(NSString *)[msgThreadDict objectForKey:#"isGroup"] isEqualToString:#"1"]) {
chatVC.isGroup = YES;
}else{
chatVC.isGroup = NO;
}
chatVC.src = #"list";
WELogInfo(#"click message");
[self.navigationController pushViewController:chatVC animated:YES];
}
#end
With the update and the changes using those trailing swipe actions there is another View appended before each time I delete an entry (until it doesn't work anymore). I've tried disabling the full trail or implementing iOS 11 trailingSwipeActionsConfigurationForRowAtIndexPath but I can't resolve this issue so far.
Do you see something wrong in the code? The main controller code is in another file.
Try reloading after you delete, after this line
[self.tableView endUpdates];
I think you removed the data from messageArray but as you are not reloading just after that so table view count is still 2 and you are reloading inside the block which might be taking time.
And one more thing you already removing data from messageArray, and then removing from db, So if you fail to remove it from db you are showing its not removed but for user it will be removed, as its no longer in message array
Here is my code which handles multiple selection of UITableview Cell properly.
Now, my question is here I had create two array in which one stores array data and second stores selected data. But, I want to do this using only one array. someone had given me solution that it can be done using KVC (valueForKeyPath) by giving key. But I have no exact idea how to do it.
If anyone knows please help me.
#import "NewTableViewController.h"
#implementation NewTableViewController
#synthesize attTableData ;
#synthesize arrSelectionData ;
- (void)viewDidLoad
{
[super viewDidLoad];
self.attTableData=[NSArray arrayWithObjects:#"Dhosa",#"Kahman",#"Dhokla",#"Handvo",#"chodafadi",#"Muthiya",#"Medu Vada",#"Patra",#"Thepla",#"Fafda",#"Gota",#"gathiya",#"Idali",#"Dalvada",#"Samosa",nil];
self.arrSelectionData=[NSMutableArray array];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.attTableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
if([self.arrSelectionData containsObject:indexPath])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
cell.textLabel.text=[self.attTableData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arrSelectionData containsObject:indexPath])
{
[self.arrSelectionData removeObject:indexPath];
}
else
{
[self.arrSelectionData addObject:indexPath];
}
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//[tableView reloadData];
}
#end
Solution ::
Data in "Recipe List" File
[0]{
Item = Thepla;
selected = 0;
},
[1]
{
Item = Gota;
selected = 0;
},
[2]
{
Item = Handvo;
selected = 0;
},
[3]
{
Item = Idali;
selected = 0;
},
[4]
{
Item = Dalvada;
selected = 0;
},
Now My TableViewController
#import "NewTableViewController.h"
#import "TableViewCell.h"
#implementation NewTableViewController
#synthesize attTableData ;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Recipe List" ofType:#"plist"];
attTableData = [[NSMutableArray alloc]initWithContentsOfFile:path];
attTableData = (NSMutableArray *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)attTableData, kCFPropertyListMutableContainers));
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.attTableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"UserCell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
NSDictionary * dicTemp = [attTableData objectAtIndex:indexPath.row];
// NSNumber* attendingObject = [dicTemp objectForKey:#"selected"];
if([dicTemp objectForKey:#"selected"] == [NSNumber numberWithBool:NO])
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
cell.lbl.text=[[self.attTableData objectAtIndex:indexPath.row]objectForKey:#"Item"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSMutableDictionary * dic = [attTableData objectAtIndex:indexPath.row];
//NSNumber* attendingObject = [dic objectForKey:#"selected"];
if ([dic objectForKey:#"selected"] == [NSNumber numberWithBool:NO])
{
[dic setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
}
else
{
[dic setValue:[NSNumber numberWithBool:NO] forKey:#"selected"];
}
[attTableData replaceObjectAtIndex:indexPath.row withObject:dic];
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
#end
If you want to do it using a single array, instead of doing like this
self.attTableData=[NSArray arrayWithObjects:#"Dhosa",#"Kahman",#"Dhokla",#"Handvo",#"chodafadi",#"Muthiya",#"Medu Vada",#"Patra",#"Thepla",#"Fafda",#"Gota",#"gathiya",#"Idali",#"Dalvada",#"Samosa",nil];
Create a model class for your items
//pseudo code
class Item{
name = "Dhosa"
selected = false
}
So attTableData will be
self.attTableData=[Item1, Item2];
Now when you make a selection you can set the selected property of the item. In cellForRow check this property and set setAccessoryType.
I am creating a today extension for my app, but there are some errors that I can't quite understand:
First:
Everything is Ok on the storyboard, but the button doesn't appear on the widget.
Second: When the tableview has more than one cell, the last cell gets cut.
Third: CellForRow is called, but don't change anything on the cell (Label is still "Label").
http://i.stack.imgur.com/Jp31V.png
Here's my Widget code:
#implementation TodayViewController{
NSMutableArray *listaFavoritos;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.widgetTableView.delegate = self;
self.widgetTableView.dataSource = self;
[self updateTableView];
self.preferredContentSize = self.widgetTableView.frame.size;
}
- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResultFailed
// If there's no update required, use NCUpdateResultNoData
// If there's an update, use NCUpdateResultNewData
completionHandler(NCUpdateResultNewData);
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
}
return self;
}
- (void)userDefaultsDidChange:(NSNotification *)notification {
[self updateTableView];
}
- (void)updateTableView {
listaFavoritos = [[NSMutableArray alloc] init];
//listaFavoritos = [[self readArrayWithCustomObjFromUserDefaults:#"listaFavs"] mutableCopy];
[listaFavoritos addObject:#"test1"];
[listaFavoritos addObject:#"test2"];
NSLog(#"%#", listaFavoritos);
}
-(NSArray *)readArrayWithCustomObjFromUserDefaults:(NSString*)keyName
{
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:#"group.com.kazoowa.timers"];
NSData *data = [sharedDefaults objectForKey:keyName];
NSArray *myArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[sharedDefaults synchronize];
return myArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listaFavoritos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"WidgetCell" forIndexPath:indexPath];
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
NSLog(#"CellForRow");
return cell;
}
1)For your second problem, your cellIdentifier in tableView:cellForRowAtIndexPath will be "static" like this :
static NSString *cellName = #"WidgetCell";
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName forIndexPath:indexPath];
2)this condition will be never execute because it's never nil :
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
replace it by this :
if (cell != nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
3)Please use Pragma Mark for separate properly your code like below:
#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listaFavoritos count];
}
#pragma mark-UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
WidgetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"WidgetCell" forIndexPath:indexPath];
if (cell == nil)
{
cell.nomeTimer.text = [listaFavoritos objectAtIndex:indexPath.row];
}
NSLog(#"CellForRow");
return cell;
}
Hope it helps :)
Try it :
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellName = #"WidgetCell";
WidgetTableViewCell *cell = (WidgetTableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellName];
if (cell == nil) {
cell = [[WidgetTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
}
cell.textLabel.text = [listaFavoritos objectAtIndex:indexPath.row];;
return cell;
}
DETAILVIEW
here's the detailview code showing the erroneous sections.howing the details of different sections of cars,such as suv,sedan,hatchback.this code show different cars of types of suvs,sedans,hatchbacks in forms of a
- (void)viewDidLoad
{
Hatchback = [[NSMutableArray alloc]initWithObjects:#"Hyundai i10",#"Hyundai i20",#"Maruti Suzuki Swift",#"Maruti Suzuki wagonR",#"Honda brio",#"Ford figo", nil];
SUV = [[NSMutableArray alloc]initWithObjects:#"Tata safari storme",#"Mahindra scorpio",#"Mahindra xuv 500",#"Renault duster", nil];
Sedan = [[NSMutableArray alloc]initWithObjects:#"Honda city",#"Maruti Suzuki dzire",#"Hyundai verna",#"Skoda octavia",#"Honda civic",#"Honda amaze",#" Ford fiesta", nil];
HatchbackImg = [[NSMutableArray alloc]initWithObjects:#"i10.jpg",#"i20.jpg",#"Swift.jpeg",#"wagonR.jpg",#"brio.jpg",#"figo.jpg",#"indica.jpg",#"beat.jpg",nil];
SUVImg = [[NSMutableArray alloc]initWithObjects:#"safari.jpg",#"scorpio.jpg",#"xuv.jpg",#"duster.jpg", nil];
SedanImg = [[NSMutableArray alloc]initWithObjects:#"city.jpg",#"dzire.jpg",#"verna.jpg",#"octavia.jpg",#"civic.jpg",#"amaze.jpg",#"fiesta.jpg", nil];
[super viewDidLoad];
self.tableView.backgroundColor = [UIColor brownColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
//return 0;
if (Carint ==0) {
return [Hatchback count];
} else if (Carint ==1) {
return [SUV count];
} else if (Carint ==2) {
return [Sedan count];
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
- (UIImage *)imageForRow:(NSUInteger)row
{
if (Carint == 0) {
return [UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
} else if (Carint == 1) {
return [UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
} else if (Carint == 2) {
return [UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
}
return nil;
}
- (NSString *)titleForRow:(NSUInteger)row
{
if (Carint == 0) {
return [Hatchback objectAtIndex:indexPath.row];
} else if (Carint == 1) {
return [SUV objectAtIndex:indexPath.row];
} else if (Carint == 2) {
return [Sedan objectAtIndex:indexPath.row];
}
return nil;
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
cell.textLabel.text = [self titleForRow:indexPath.row];
cell.imageView.image = [self imageForRow:indexPath.row];
if (Carint == 0) {
cell.imageView.image=[UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
cell.textLabel.text =[Hatchback objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
} else if (Carint == 1) {
cell.imageView.image=[UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [SUV objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
} else if (Carint == 2) {
cell.imageView.image=[UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [Sedan objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc]init];
[cell.contentView addSubview:imageView];
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
// Configure the cell...
return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"cellBg1.png"]];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (Carint == 0)
{
NSString *imageName = [HatchbackImg objectAtIndex:indexPath.row];
//[UIImageView setImage:[SedanImg objectAtIndex:indexPath.row]];
// [UIImageView setImage:[SedanImg objectAtIndex:indexPath.row]];
}
else if (Carint ==1)
{
NSString *imageName = [SUVImg objectAtIndex:indexPath.row];
}
else if (Carint ==2)
{
NSString *imageName = [SedanImg objectAtIndex:indexPath.row];
}
NSString *carName = [self titleForRow:indexPath.row];
UIImage *carImage = [self imageForRow:indexPath.row];
// Navigation logic may go here. Create and push another view controller.
carSelectViewController *carDetailViewController = [[carSelectViewController alloc] initWithNibName:#"carSelectViewController" bundle:nil];
carDetailViewController.carName = carName;
carDetailViewController.carImage = carImage;
[self.navigationController pushViewController:carDetailViewController animated:YES];
}
#end
You should not be storing data in the cells of a table. The cells of a table are there to display information.
First, you seem to be using an iVar Carint to display different sets of cars. First, all variables should have lowercase first letters. Second, this is a bad idea.
By doing this you are strongly coupling the table to the data it is displaying. I'll ignore this for now though.
Second, you should also be using a custom UITableViewCell subclass to create UIImageViews etc... but I'll ignore this too.
Third, you should create a Class called Car. Then give the class Car two properties, name and image and actually you could give it type too but again I'll ignore this.
NOTE just because I am ignoring them doesn't mean you should too. Think of these first three as hints of what to work on next.
Fourth, create a function that will return the image for the row. Like this...
- (UIImage *)imageForRow:(NSUInteger)row
{
if (Carint == 0) {
return [UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
} else if (Carint == 1) {
return [UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
} else if (Carint == 2) {
return [UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
}
return nil;
}
and the title. Like this...
- (NSString *)titleForRow:(NSUInteger)row
{
if (Carint == 0) {
return [Hatchback objectAtIndex:indexPath.row];
} else if (Carint == 1) {
return [SUV objectAtIndex:indexPath.row];
} else if (Carint == 2) {
return [Sedan objectAtIndex:indexPath.row];
}
return nil;
}
This means that you can change your current methods like so...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
cell.textLabel.text = [self titleForRow:indexPath.row];
cell.imageView.image = [self.imageForRow:indexPath.row];
return cell;
}
and...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *carName = [self titleForRow:indexPath.row];
UIImage *carImage = [self imageForRow:indexPath.row];
// Navigation logic may go here. Create and push another view controller.
// OMG! Fix the naming conventions. Class names should start with uppercase letters.
carSelectViewController *carDetailViewController = [[carSelectViewController alloc] initWithNibName:#"carSelectViewController" bundle:nil];
// These won't work until you do the next bit.
carDetailViewController.carName = carName;
carDetailViewController.carImage = carImage;
// Pass the selected object to the new view controller.
[self.navigationController pushViewController: carDetailViewController animated:YES];
}
Next, add properties to the "detail view controller" like this...
#interface carSelectViewController : UIViewController
#property NSString *carName;
#property UIImage *carImage;
#end
These are then being set by the previous view controller.
Finally, use the values of these properties to display the data.
- (void)viewDidLoad
{
self.title = self.carName;
imageView.image = self.carImage;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
For more information about doing this and especially working on those first three points you can see here...
http://www.raywenderlich.com
**CARDETAILVIEWCONTROLLER**
- (void)viewDidLoad
{
[self showData];
[super viewDidLoad];
self.tableView.backgroundColor = [UIColor brownColor];
}
-(void) showData
{
Hatchback = [[NSMutableArray alloc]init];
SUV = [[NSMutableArray alloc]init];
Sedan = [[NSMutableArray alloc]init];
//Hatchback
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai i10",#"name",#"i10.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai i20",#"name",#"i20.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Maruti Suzuki Swift",#"name",#"Swift.jpeg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Maruti Suzuki wagonR",#"name",#"wagonR.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda Brio",#"name",#"brio.jpg",#"image",nil]];
[Hatchback addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Ford figo",#"name",#"figo.jpg",#"image",nil]];
//SUV
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Tata safari storme",#"name",#"safari.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Mahindra scorpio",#"name",#"scorpio.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Mahindra xuv 500",#"name",#"xuv.jpg",#"image",nil]];
[SUV addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Renault duster",#"name",#"duster.jpg",#"image",nil]];
//Sedan
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda city",#"name",#"city.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"MarutiSuzuki dzire",#"name",#"dzire.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Hyundai verna",#"name",#"verna.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Skoda octavia",#"name",#"octavia.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda civic",#"name",#"civic.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Honda amaze",#"name",#"amaze.jpg",#"image",nil]];
[Sedan addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Ford fiesta",#"name",#"fiesta.jpg",#"image",nil]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
if (Carint ==0) {
return [Hatchback count];
}
if (Carint ==1) {
return [SUV count];
}
if (Carint ==2) {
return [Sedan count];
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyCell"];
if (Carint == 0)
{
cell.imageView.image=[UIImage imageNamed:[HatchbackImg objectAtIndex:indexPath.row]];
cell.textLabel.text =[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"name"];
}
if (Carint == 1)
{
cell.imageView.image=[UIImage imageNamed:[SUVImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [[SUV objectAtIndex:indexPath.row] objectForKey:#"name"];
}
if (Carint == 2)
{
cell.imageView.image=[UIImage imageNamed:[SedanImg objectAtIndex:indexPath.row]];
cell.textLabel.text = [[Sedan objectAtIndex:indexPath.row ]objectForKey:#"name"];
}
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
return cell;
}
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"cellBg1.png"]];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
carSelectViewController *car = [[carSelectViewController alloc]initWithNibName:#"carSelectViewController" bundle:nil];
if (Carint == 0)
{
car.carImageString = [[NSString alloc]initWithString:[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[Hatchback objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[Hatchback objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
else if (Carint ==1)
{
car.carImageString = [[NSString alloc]initWithString:[[SUV objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[SUV objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[SUV objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
else if (Carint ==2)
{
car.carImageString = [[NSString alloc]initWithString:[[Sedan objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.carLabelString = [[NSString alloc]initWithString:[[Sedan objectAtIndex:indexPath.row]objectForKey:#"image"]];
car.title = [[Sedan objectAtIndex:indexPath.row]objectForKey:#"name" ];
}
[self.navigationController pushViewController:car animated:YES];
}
#end
**CARSELECTVIEWCONTROLLER
#synthesize carImageString,carLabelString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
NSString *localImgName;
- (void)viewDidLoad
{
carImage.image = [UIImage imageNamed:carImageString];
carLabel.text = carLabelString;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnBook:(id)sender {
carBookViewController *Book = [[carBookViewController alloc]initWithNibName:#"carBookViewController" bundle:nil];
[self.navigationController pushViewController: Book animated:YES];
}
#end
I have tried the method of using nsdictionaries for key pair values of images & text together to make the code simpler(i guess).it goes well with the requirement of the app as well to show text & images together on the next view.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NextViewController *viewcontroller=[NextViewController alloc]init];
viewcontroller.image=[tableView cellForRowAtIndexPath:indexPath].imageView.image;
}
Then either push or present this view Controller to show.
viewcontroller.image is cusotm property in ur next class
then on viewdidload method
set the imageView's image property to self.image
I am trying to create a method that changes the string object "tableColorName" to the cell selected. The tableData NSArray consists of object: "red","blue","green". I want to save the string "tableColorName" to redColor if red is selected, blueColor if blue, greenColor if green. After the cell is selected I want the viewController to go back to the root. I appreciate your help in advance:
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int theRow = indexPath.row;
NSString *tableColorName;
tableColorName = [[NSString alloc] initWithString:([_tableData [theRow] stringValue],#"Color")];
[self.navigationController popToRootViewControllerAnimated:YES];
}
//first of all take one NSArray and
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.colorNames = [[NSArray alloc] initWithObjects:#"Red", #"Green",
#"Blue", #"Indigo", #"Violet", nil];
}
// Implement Table method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
self.navigationItem.title=#"Colors";
UIImage *cellImage = [UIImage imageNamed:#"a.png"];
cell.imageView.image = cellImage;
NSString *colorString = [self.colorNames objectAtIndex: [indexPath row]];
cell.textLabel.text = colorString;
NSString *subtitle = [NSString stringWithString: #"All about the color "];
subtitle = [subtitle stringByAppendingFormat:colorString];
cell.detailTextLabel.text = subtitle;
return cell;
}
- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
{
int idx = indexPath.row;
obj.lbl.text=[#"You select "stringByAppendingString:[colorNames objectAtIndex:idx]];
[self popToViewController animated:YES];
}
Try this ::
NSArray *arr;
NSString *tableColorName; // Use in AppDelegate
- (void)viewDidLoad
{
arr = [[NSArray alloc] initWithObjects:#"Red", #"Green", #"Blue", nil];
}
Table View Methods ::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.title.text = [NSString stringWithFormat:#"%#", [arr objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
app.tableColorName = [NSString StringWithFormat:#"%# Color", [arr objectAtIndex:indexPath.row]];
[self.navigationController popToRootViewControllerAnimated:YES];
}
Then, access by app.tableColorName whenever you want to display.
Thanks.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//do whatever with the selected cell.
//go back to the root
}