I am new in iOS and I am facing problem regarding to delete image
For delete I am using code like this
In DidFinishLoading
imageArray =[[NSMutableArray alloc]init];
for (int i=0; i<idarray.count; i++) {
[imageArray addObject:[UIImage new]];
}
In CellForrowAtIndexPath
cell.btnRemove.tag=indexPath.row;
[cell.btnRemove addTarget:self action:#selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
Button Click
-(void)btnRemoveClick:(UIButton *)sender
{
UIAlertView *Alertview =[[UIAlertView alloc] initWithTitle:#"Warning!" message:#"Are You Sure you want to delete Image" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
[Alertview show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
[imageArray removeObjectAtIndex:CurrentIndexPath];
[imageArray addObject:[UIImage new]];
[Audittable reloadData];
}
But When I delete image image get swap as in the image
enter image description here
enter image description here
CellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
AuditNextTableViewCell *cell = (AuditNextTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AuditNextTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
cell.audittitlelbl.text=[NSString stringWithFormat:#"%#",[idarray objectAtIndex:indexPath.row]];
cell.nameidlbl.text=[NSString stringWithFormat:#"%#",[CheckpointNameIDArray objectAtIndex:indexPath.row]];
cell.passlbl.text=[NSString stringWithFormat:#"%#",[Passarray objectAtIndex:indexPath.row]];
cell.faillbl.text=[NSString stringWithFormat:#"%#",[Failarray objectAtIndex:indexPath.row]];
cell.warninglbl.text=[NSString stringWithFormat:#"%#",[Warningarray objectAtIndex:indexPath.row]];
cell.nalbl.text=[NSString stringWithFormat:#"%#",[NAarray objectAtIndex:indexPath.row]];
cell.popuplbl.text=[NSString stringWithFormat:#"%#",[Popuparray objectAtIndex:indexPath.row ]];
// cell.remarklbl.text=[NSString stringWithFormat:#"%#",[PFWNAArray objectAtIndex:indexPath.row]];
DataModel *model2 = [AuditTextBoxarray objectAtIndex:indexPath.row];
cell.lblAuditTextBox.text=model2.AuditTextBoxString;
//cell.lblAuditTextBox.text=[NSString stringWithFormat:#"%#",[AuditTextBoxarray objectAtIndex:indexPath.row]];
cell.AuditCountlbl.text=[NSString stringWithFormat:#"%ld)", (long)indexPath.row +1];
cell.CaptureImage.image = [imageArray objectAtIndex:indexPath.row];
// tag add on buttons
cell.passbtn.tag = indexPath.row;
cell.failbtn.tag = indexPath.row;
cell.wipbtn.tag = indexPath.row;
cell.nabtn.tag = indexPath.row;
cell.Photobtn.tag=indexPath.row;
cell.btnRemove.tag=indexPath.row;
//method add on buttons
[cell.passbtn addTarget:self action:#selector(btnP:) forControlEvents:UIControlEventTouchUpInside];
[cell.failbtn addTarget:self action:#selector(btnF:) forControlEvents:UIControlEventTouchUpInside];
[cell.wipbtn addTarget:self action:#selector(btnW:) forControlEvents:UIControlEventTouchUpInside];
[cell.nabtn addTarget:self action:#selector(btnNA:) forControlEvents:UIControlEventTouchUpInside];
[cell.Photobtn addTarget:self action:#selector(btnphotoClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.btnRemove addTarget:self action:#selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"AuditPost"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
ComplareArray=[devices valueForKey:#"checkpointid"];
countcellbtn.text=[NSString stringWithFormat:#"%lu",(unsigned long)ComplareArray.count];
if (![arrIndexPaths containsObject:indexPath])
{
[arrIndexPaths addObject:indexPath];
}
if (![PassarrIndexPaths containsObject:indexPath])
{
[PassarrIndexPaths addObject:indexPath];
}
//background color change on button
DataModel *model = [arrData objectAtIndex:indexPath.row];
if([model.strSelected isEqualToString:#"P"])
{
cell.passbtn.backgroundColor = [UIColor redColor];
}
else if([model.strSelected isEqualToString:#"F"])
{
cell.failbtn.backgroundColor = [UIColor yellowColor];
}
else if([model.strSelected isEqualToString:#"W"])
{
cell.wipbtn.backgroundColor = [UIColor orangeColor];
}
else if([model.strSelected isEqualToString:#"NA"])
{
cell.nabtn.backgroundColor = [UIColor blueColor];
}
else if ([model.strSelected isEqualToString:#"PA"])
{
cell.passbtn.backgroundColor=[UIColor greenColor];
}
else if ([model.strSelected isEqualToString:#"NAA"])
{
cell.nabtn.backgroundColor=[UIColor blueColor];
}
else
{
cell.passbtn.backgroundColor = [UIColor lightGrayColor];
cell.failbtn.backgroundColor = [UIColor lightGrayColor];
cell.wipbtn.backgroundColor = [UIColor lightGrayColor];
cell.nabtn.backgroundColor = [UIColor lightGrayColor];
}
[cell.contentView.layer setBorderColor:[UIColor blackColor].CGColor];
[cell.contentView.layer setBorderWidth:0.5f];
return cell;
}
Related
I am working on chat application. Actually i have 3 arrays. First array stores user name and second array stores chat message and third array stores images. I am picking image from photo gallery.
When user sends any message to the chat wall I display message in bubble.
So I'm writing some conditions like the below:
if arr2 value is not null then displaying chat message
if arr3 value is not null displaying image in chat bubble
if arr2 value is null then i want to hide lbldesc and show only imv gallery image
if arr3 value is null then hide imv gallery image and enable lblDesc
But i got exception like this:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** NSAllocateMemoryPages(4294967295) failed'`
Here is my code:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.selectionStyle=UITableViewCellSelectionStyleNone;
if (itemsDataArr.count>0) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 3, 250, 80)];
imgView.image = [UIImage imageNamed:#"speech-bubble-2-hi.png"];
imgView.layer.borderColor = [UIColor clearColor].CGColor;
imgView.tag = 5;
[cell.contentView addSubview:imgView];
NSArray *arr1=[[NSArray alloc]init];
arr1=[itemsUserNameArr objectAtIndex:indexPath.row];
NSString *strval=[arr1 objectAtIndex:0];
lblTitle=[[UILabel alloc]initWithFrame:CGRectMake(50, 5, 150, 20)];
lblTitle.highlightedTextColor=[UIColor whiteColor];
[cell.contentView addSubview:lblTitle];
[lblTitle setFont:[UIFont boldSystemFontOfSize:14]];
lblTitle.text=strval;
[imgView addSubview:lblTitle];
NSArray *arr2=[[NSArray alloc]init];
arr2=[itemsDataArr objectAtIndex:indexPath.row];
NSArray *arr3=[[NSArray alloc]init];
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr2 isEqual:#""])
{
NSString *strmsg=[arr2 objectAtIndex:0];
lblDesc=[[UILabel alloc]initWithFrame:CGRectMake(50, 22, 300, 20)];
lblDesc.highlightedTextColor=[UIColor whiteColor];
lblDesc.font=[UIFont systemFontOfSize:12.0];
[cell.contentView addSubview:lblDesc];
[lblDesc setHidden:NO];
lblDesc.text=strmsg;
[imgView addSubview:lblDesc];
// imv.hidden=YES;
// [imv setHidden:true];
}
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr3 isEqual:nil])
{
NSString *strImg=[arr3 objectAtIndex:0];
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:strImg]];
//Now data is decoded. You can convert them to UIImage
imv = [[UIImageView alloc]initWithFrame:CGRectMake(93,12, 50, 50)];
imv.image=[UIImage imageWithData:data];
[imgView addSubview:imv];
[lblDesc setHidden:YES];
// lblDesc.hidden=YES;
}
}
return cell;
}
I've used PTSMessagingCell from here:
I've used messages array for texts/images. This is a ruf sample that may help you.
#import "ViewController.h"
#import "PTSMessagingCell.h"
#interface ViewController ()
{
NSMutableArray *messages;
UITextView *sendMsg;
UITableView *chatTable;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
messages = [[NSMutableArray alloc] initWithObjects:#"Hello",[UIImage imageNamed:#"download.jpeg"],#"Check This Out", nil];
chatTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-100)];
chatTable.delegate = self;
chatTable.dataSource = self;
chatTable.separatorColor = [UIColor clearColor];
[self.view addSubview:chatTable];
chatTable.backgroundColor = [UIColor clearColor];
sendMsg = [[UITextView alloc]initWithFrame:CGRectMake(0, chatTable.frame.size.height, self.view.frame.size.width-100, 100)];
sendMsg.textColor = [UIColor blackColor];
sendMsg.delegate = self;
sendMsg.backgroundColor = [UIColor whiteColor];
sendMsg.layer.cornerRadius = 3.0f;
[self.view addSubview:sendMsg];
UIButton *sendMsgbtn = [[UIButton alloc]initWithFrame:CGRectMake(sendMsg.frame.size.width, chatTable.frame.size.height, 100, 100)];
[sendMsgbtn setTitle:#"SEND" forState:UIControlStateNormal];
sendMsgbtn.backgroundColor = [UIColor redColor];
[sendMsgbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sendMsgbtn addTarget:self action:#selector(sendClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendMsgbtn];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[chatTable addGestureRecognizer:tapGestureRecognizer];
}
-(void)sendClicked{
[sendMsg resignFirstResponder];
[chatTable reloadData];
}
#pragma mark - TableView Delegate and DataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*This method sets up the table-view.*/
static NSString* cellIdentifier = #"messagingCell";
PTSMessagingCell * cell = (PTSMessagingCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[PTSMessagingCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
return [(UIImage *)[messages objectAtIndex:indexPath.row] size].height;
}
else{
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
CGSize messageSize = [PTSMessagingCell messageSize:goodMsg];
NSLog(#"%f",messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f);
return messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f;
}
}
-(void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
if (messages.count>0) {
PTSMessagingCell* ccell = (PTSMessagingCell*)cell;
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
ccell.sent = YES;
ccell.avatarImageView.image = [UIImage imageNamed:[messages objectAtIndex:indexPath.row]];
ccell.messageLabel.text = #"";
}
else{
ccell.sent = YES;
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
ccell.messageLabel.text = [messages objectAtIndex:indexPath.row];
}
ccell.timeLabel.text = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[ccell addGestureRecognizer:tapGestureRecognizer];
}
}
-(void)tapReceived:(UITapGestureRecognizer *)tapGestureRecognizer
{
// do something, like dismiss your view controller, picker, etc., etc.
[sendMsg resignFirstResponder];
}
Hope this helps.
Create a custom cell and load images in background thread will give better UI performance
I'm parsing image's from a JSON-file on my server. Right now I'm setting the heightForRowAtIndexPath to return 389. But some of the images get stretched now. I need the cell to adjust it's size based on the image height. Right now, my code looks like this:
#implementation Pictures
#synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
#synthesize btnFaceBook, btnTwitter, btnTwitter2;
#synthesize strURLToLoad;
#synthesize movies;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl setTintColor:[UIColor greenColor]];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
strURLToLoad = [[NSMutableString alloc] init];
[btnFaceBook setTitle:#"link-to-json.com/json.php" forState:UIControlStateDisabled];
[btnTwitter setTitle:#"link1-to-json.com/json.php" forState:UIControlStateDisabled];
[btnTwitter2 setTitle:#"link2-to-json.com/json.php" forState:UIControlStateDisabled];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[self.navigationController setNavigationBarHidden:YES];
self.tableView.separatorColor = [UIColor clearColor];
// Setting Up Activity Indicator View
self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicatorView.color = [UIColor greenColor];
self.activityIndicatorView.hidesWhenStopped = YES;
self.activityIndicatorView.center = self.view.center;
[self.view addSubview:self.activityIndicatorView];
[self.activityIndicatorView startAnimating];
self.tableView.separatorColor = [UIColor clearColor];
// Initializing Data Source
movies = [[NSMutableArray alloc] init];
[self btnFromTabBarClicked:btnFaceBook];
}
- (void)loadJSONFromCurrentURL
{
[self.activityIndicatorView startAnimating];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[movies setArray:JSON];
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
//Unselect all 3 buttons
btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;
//Select the button that was clicked
sender.selected = YES;
//Set the string of an NSMutableString property called strURLToLoad with the URL
//The URL is pre stored in the text of the UIButton in the Disabled text.
[strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];
//Load the URL
[self loadJSONFromCurrentURL];
}
- (IBAction)showButtonMenu {
[self.frostedViewController presentMenuViewController];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.movies && self.movies.count) {
return self.movies.count;
} else {
return 0;
}
}
//here I want the cell to adjust it's size based on the image height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 389;
}
- (NSString *)getTextKey
{
return btnTwitter.selected?#"title":#"title";
}
- (NSString *)getPostedKey
{
return btnTwitter2.selected?#"uploaded":#"published";
}
- (NSString *)getTwitterName
{
return btnTwitter.selected?#"celebtag":#"celebname";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
static NSString *Identifier1 = #"TableHeaderView";
TableHeaderView *cell = [tableView dequeueReusableCellWithIdentifier:Identifier1];
if (cell == nil) {
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:#"TableHeaderView" owner:self options:nil];
cell = (TableHeaderView *)[nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
} else {
static NSString *simpleTableIdentifier = #"PicturesObject";
PicturesObject *cell = (PicturesObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PicturesObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *strText = [movie objectForKey:[self getTextKey]];
NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:#"link"]];
[cell.pic setImageWithURL:url placeholderImage:[UIImage imageNamed:#"placeholder"]];
cell.published.text = [movie objectForKey:[self getPostedKey]];
cell.title.text = [movie objectForKey:#"title"];
cell.twitterName.text = [movie objectForKey:[self getTwitterName]];
return cell;
} return 0;
}
#end
At first you need some variable to save image height - array or dictionary, then when you get the image save the height and call [tableView reloadRowAtIndexPath:indexPath]
and in
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
return proper height saved before
I have a NSMutableArray in a view where I parse some JSON data to a Table View. I also have three buttons on the bottom: Button 1, Button 2, Button 3. If I select Button 2, the JSON data string changes to Link 2 etc...
Now, when I click on a cell, the value (text) passes to a UITextView in the Second View Controller. But what I want, is to also pass which button that was pressed, so the string name to the UITextView parses correct. Because now, when I select for example button 2 and click on a cell, the Text View on Second View Controller gets blank, because I only set the string name to #"message", and the string name for the text when selected Button 2 is #"tweet".
Here's my code:
#interface DEMOSecondViewController ()
#end
#implementation DEMOSecondViewController
#synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView;
#synthesize fontForCellText;
#synthesize btnFaceBook, btnTwitter, btnTwitter2;
#synthesize strURLToLoad;
#synthesize movies;
- (IBAction)showButtonMenu {
[self.frostedViewController presentMenuViewController];
}
- (void)refresh:(UIRefreshControl *)refreshControl {
[refreshControl endRefreshing];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl setTintColor:[UIColor greenColor]];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
strURLToLoad = [[NSMutableString alloc] init];
[btnFaceBook setTitle:#"link-1.com/json.php" forState:UIControlStateDisabled];
[btnTwitter setTitle:#"link-2.com/json.php" forState:UIControlStateDisabled];
[btnTwitter2 setTitle:#"link-3.com/json.php" forState:UIControlStateDisabled];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnFaceBook setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_selected.png"] forState:UIControlStateNormal];
[btnTwitter2 setBackgroundImage:[UIImage imageNamed:#"tab_unselected.png"] forState:UIControlStateSelected];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PostsObject" owner:self options:nil];
PostsObject *cell = [nib objectAtIndex:0];
fontForCellText = cell.title.font;
cellTextWidth = cell.title.frame.size.width;
cellHeightExceptText = cell.frame.size.height - cell.title.frame.size.height;
[self.navigationController setNavigationBarHidden:YES];
self.tableView.separatorColor = [UIColor clearColor];
// Setting Up Activity Indicator View
self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicatorView.color = [UIColor greenColor];
self.activityIndicatorView.hidesWhenStopped = YES;
self.activityIndicatorView.center = self.view.center;
[self.view addSubview:self.activityIndicatorView];
[self.activityIndicatorView startAnimating];
self.tableView.separatorColor = [UIColor clearColor];
// Initializing Data Source
movies = [[NSMutableArray alloc] init];
[self btnFromTabBarClicked:btnFaceBook];
}
- (void)loadJSONFromCurrentURL
{
[self.activityIndicatorView startAnimating];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURLToLoad]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[movies setArray:JSON];
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
//This is where I change the data source when selecting a button
- (IBAction)btnFromTabBarClicked:(UIButton *)sender
{
btnFaceBook.selected = btnTwitter.selected = btnTwitter2.selected = NO;
sender.selected = YES;
[strURLToLoad setString:[sender titleForState:UIControlStateDisabled]];
[self loadJSONFromCurrentURL];
}
// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return movies.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
static NSString *Identifier1 = #"TableHeaderView";
TableHeaderView *cell = [tableView dequeueReusableCellWithIdentifier:Identifier1];
if (cell == nil) {
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:#"TableHeaderView" owner:self options:nil];
cell = (TableHeaderView *)[nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor clearColor];
return cell;
}
} else {
static NSString *Identifier2 = #"PostsObject";
PostsObject *cell = [tableView dequeueReusableCellWithIdentifier:Identifier2];
if (cell == nil) {
NSArray *nib= [[NSBundle mainBundle] loadNibNamed:#"PostsObject" owner:self options:nil];
cell = (PostsObject *)[nib objectAtIndex:0];
cell.backgroundColor = [UIColor clearColor];
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *strText = [movie objectForKey:[self getTextKey]];
CGRect rect = cell.title.frame;
rect.size.height = [self getHeightForText:strText];
cell.title.frame = rect;
cell.title.text = strText;
cell.arrow.center = CGPointMake(cell.arrow.frame.origin.x, rect.origin.y + rect.size.height/2);
cell.published.text = [movie objectForKey:[self getPostedTime]];
cell.twitterName.text = [movie objectForKey:[self getTwitterName]];
return cell;
}
return 0;
}
//Here I am passing the selected cell data to (PostsNextView). I want to pass the string values of button 1, button 2 and button 3. How?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
PostsNextView *newView = [[PostsNextView alloc] init];
newView.theMovie = movie;
[self.navigationController pushViewController:newView animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0) {
return 224;
} else {
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
NSString *strText = [movie objectForKey:[self getTextKey]];
CGFloat cellHeight = cellHeightExceptText + [self getHeightForText:strText];
return cellHeight;
}
}
- (NSString *)getTextKey
{
return btnTwitter.selected?#"tweet":#"message";
}
- (NSString *)getPostedTime
{
return btnTwitter.selected?#"posted":#"published";
}
- (NSString *)getTwitterName
{
return btnTwitter2.selected?#"user":#"celebname";
}
- (CGFloat)getHeightForText:(NSString *)strText
{
CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
CGSize labelSize = [strText sizeWithFont:fontForCellText constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"labelSize.height = %f",labelSize.height);
return labelSize.height;
}
#end
As you can see in the first view, I have 3 different links I'm parsing. How can I set an if-statement in viewDidLoad in PostsNextView? Like, if the btnFacebook is selected: textView.text = [theMovie objectForKey:#"message"]; and if btnTwitter is selected: textView.text = [theMovie objectForKey:#"tweet"]; ?
Would really appreciate a solution!
Revised Answer (This will be high level):
Add Tag Values to each of your buttons
When a button is clicked you can get its tag with the getTag (also tag can be set with setTag) call - please check the API for details
As you are programatically loading your next view controller when you create it
PostsNextView *newView = [[PostsNextView alloc] init];
newView.theMovie = movie;
// You could add a call here to set the value
[newView setTheVaue:valueIWantToSet]
You would make a property called TheValue in your newView controller
When you actually make your call to change to the new view controller
[self.navigationController pushViewController:newView animated:YES];
The data value you desire will already be set.
I am trying to load image asynchronously in a UIImage that resides in a table view cell. sometimes it shows the image from another cell for a second before it displays the correct one.
This is the code I am using
[[TMCache sharedCache] objectForKey:post[#"gif"] block:^(TMCache *cache, NSString *key, id object) {
if (object) {
if ([self isRowZeroVisible:indexPath.section]) {
[GIFLoader loadGIFData:object to:postGif for:feedTableView];
}
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
__block NSURL* url = [NSURL URLWithString:post[#"gif"]];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req];
[loader startRequestWithResponseHandler:nil
progress:nil
completion:^(NSData* receivedData, NSInteger httpStatusCode) {
if ([self isRowZeroVisible:indexPath.section]) {
[GIFLoader loadGIFData:receivedData to:postGif for:feedTableView];
}
[[TMCache sharedCache] setObject:receivedData forKey:post[#"gif"]];
} errorHandler:nil];
});
}];
[GIFLoader loadGIFData:receivedData to:postGif for:feedTableView]; is a method I created that loads GIFs in a uiimageview. it does that in a background thread and then assigns the Image in the main thread though.
Are there certain practices that I need to follow for async loading?
I am not sure what is wrong with my code. any help would be highly appreciated
edit
//Loading stuff into tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#autoreleasepool {
//Type of Cells
static NSString *simpleTableImageIdentifier = #"gifCell";
static NSString *simpleTableBodyIdentifier = #"bodyCell";
static NSString *simpleTableActionsIdentifier = #"actionsCell";
UITableViewCell *cell = nil;
//Data that goes in the cell
NSDictionary *post = [dataArray objectAtIndex:indexPath.section];
//User info
UIImageView *userAvatar;
UILabel *postUserFullNameLabel;
UILabel *postUsername;
//GIF Date
OHAttributedLabel* gifDate = nil;
NSMutableAttributedString* gifDateString;
//Feed GIF
NSString *gifBody = [[NSString alloc]init];
OHAttributedLabel* attrLabel = nil;
NSMutableAttributedString* mas;
//Location
OHAttributedLabel* gifLocation = nil;
NSMutableAttributedString* gifLocationString;
UILabel *locationBg;
//Buttons
UIButton *btn1 =[[UIButton alloc] initWithFrame:CGRectMake(11,0,50,30)];
UIButton *btn2 =[[UIButton alloc] initWithFrame:CGRectMake(69,0,50,30)];
UIButton *btn3 =[[UIButton alloc] initWithFrame:CGRectMake(259,0,50,30)];
if (indexPath.row == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableImageIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableImageIdentifier];
}
__block UIImageView *postGif= (UIImageView *)[cell viewWithTag:104];
postGif.image = nil;
[[TMCache sharedCache] objectForKey:post[#"gif"] block:^(TMCache *cache, NSString *key, id object) {
if (object) {
if ([self isRowZeroVisible:indexPath.section]) {
[GIFLoader loadGIFData:object to:postGif for:feedTableView];
}
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
__block NSURL* url = [NSURL URLWithString:post[#"gif"]];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req];
[loader startRequestWithResponseHandler:nil
progress:nil
completion:^(NSData* receivedData, NSInteger httpStatusCode) {
if ([self isRowZeroVisible:indexPath.section]) {
[GIFLoader loadGIFData:receivedData to:postGif for:feedTableView];
}
[[TMCache sharedCache] setObject:receivedData forKey:post[#"gif"]];
} errorHandler:nil];
});
}];
postGif.layer.cornerRadius = 2.0;
postGif.layer.masksToBounds = YES;
postGif.clipsToBounds = YES;
locationBg = (UILabel *)[cell viewWithTag:106];
userAvatar = (UIImageView *)[cell viewWithTag:100];
if ([post [#"user_avatar"] length ] > 0) {
NSString *img = [#"https://d1f7i732a4e7fw.cloudfront.net/" stringByAppendingString:post [#"user_avatar"]];
[userAvatar setImageWithURL:[NSURL URLWithString:img] placeholderImage:[UIImage imageNamed:#"userDefaultPicture.png"]];
}else{
userAvatar.image = [UIImage imageNamed:#"userDefaultPicture.png"];
}
userAvatar.layer.cornerRadius = 18.0;
userAvatar.layer.borderWidth = 1.0;
userAvatar.layer.borderColor = (__bridge CGColorRef)([UIColor lightGrayColor]);
userAvatar.clipsToBounds = YES;
postUserFullNameLabel = (UILabel *)[cell viewWithTag:101];
postUserFullNameLabel.text = post[#"user_fullname"];
postUsername = (UILabel *)[cell viewWithTag:102];
postUsername.text = [NSString stringWithFormat:#"#%#",post[#"user_username"]];
gifDate = [[OHAttributedLabel alloc] initWithFrame:CGRectMake(246,9,60,21)];
gifDate.autoresizingMask = UIViewAutoresizingNone;
gifDate.centerVertically = YES;
gifDate.highlightedTextColor = [UIColor whiteColor];
gifDate.tag = 103;
gifDate.backgroundColor = [UIColor clearColor];
gifDate.extendBottomToFit = NO;
gifDateString = [NSMutableAttributedString attributedStringWithString:[NSString stringWithFormat:#"\ue003 %#",post[#"date"]]];
[gifDateString setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0]];
[gifDateString setFont:[UIFont fontWithName:#"icomoon" size:10.0] range:NSMakeRange(0,1)];
[gifDateString setTextColor:[UIColor whiteColor]];
[gifDateString setTextAlignment:kCTTextAlignmentRight lineBreakMode:kCTLineBreakByTruncatingTail];
[OHASBasicMarkupParser processMarkupInAttributedString:gifDateString];
gifDate.attributedText = gifDateString;
if (!(post[#"latitude"] == (id)[NSNull null])){
//Location of the Post
gifLocation = [[OHAttributedLabel alloc] initWithFrame:CGRectMake(165,27,141,21)];
gifLocation.autoresizingMask = UIViewAutoresizingNone;
gifLocation.centerVertically = YES;
gifLocation.highlightedTextColor = [UIColor whiteColor];
gifLocation.tag = 107;
gifLocation.backgroundColor = [UIColor clearColor];
gifLocation.extendBottomToFit = NO;
gifLocationString = [NSMutableAttributedString attributedStringWithString:[NSString stringWithFormat:#"\uf041 %#",post[#"locationName"]]];
[gifLocationString setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0]];
[gifLocationString setFont:[UIFont fontWithName:#"icomoon" size:12.0] range:NSMakeRange(0,1)];
[gifLocationString setTextColor:[UIColor whiteColor]];
[gifLocationString setTextAlignment:kCTTextAlignmentRight lineBreakMode:kCTLineBreakByTruncatingTail];
[OHASBasicMarkupParser processMarkupInAttributedString:gifLocationString];
gifLocation.attributedText = gifLocationString;
}
}
else if (indexPath.row == 1) {
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableBodyIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableBodyIdentifier];
}
//Body of GIF
// Add more from here http://www.easyapns.com/iphone-emoji-alerts
gifBody = post[#"body"];
attrLabel = [[OHAttributedLabel alloc] initWithFrame:CGRectMake(10,5,kLabelWidth,tableView.rowHeight-2*kLabelVMargin)];
attrLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
attrLabel.centerVertically = NO;
attrLabel.automaticallyAddLinksForType = NSTextCheckingAllTypes;
attrLabel.delegate = self;
attrLabel.highlightedTextColor = UIColorFromRGB(0x333333);
attrLabel.tag = kAttributedLabelTag;
attrLabel.backgroundColor = [UIColor clearColor];
attrLabel.extendBottomToFit = YES;
[cell.contentView addSubview:attrLabel];
attrLabel = (OHAttributedLabel*)[cell viewWithTag:kAttributedLabelTag];
mas = [NSMutableAttributedString attributedStringWithString:gifBody];
[mas setFont:[UIFont fontWithName:#"Helvetica Neue" size:14.0]];
[mas setTextColor:UIColorFromRGB(0x333333)];
[mas setTextAlignment:kCTTextAlignmentLeft lineBreakMode:kCTLineBreakByWordWrapping];
[OHASBasicMarkupParser processMarkupInAttributedString:mas];
attrLabel.attributedText = mas;
}
else if (indexPath.row == 2) {
cell = [tableView dequeueReusableCellWithIdentifier:simpleTableActionsIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableActionsIdentifier];
}
[self customizeButtons:btn1];
btn1.tag = (indexPath.section +1)*200;
btn1.titleLabel.font = [UIFont fontWithName:#"icomoon" size:16.0];
if ([post[#"is_Favoring"] boolValue]) {
[btn1 setTitleColor:UIColorFromRGB(0xE4717A) forState:UIControlStateNormal];
}else{
[btn1 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
}
[btn1 setTitle:#"\uf004" forState:UIControlStateNormal];
btn1.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[btn1 addTarget:self
action:#selector(favorAction:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn1];
[self customizeButtons:btn2];
btn2.tag = (indexPath.section +1)*2000;
btn2.titleLabel.font = [UIFont fontWithName:#"icomoon" size:16.0];
[btn2 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[btn2 setTitle:#"\ue000" forState:UIControlStateNormal];
[cell.contentView addSubview:btn2];
btn2.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[btn2 addTarget:self
action:#selector(commentAction:)
forControlEvents:UIControlEventTouchUpInside];
[self customizeButtons:btn3];
btn3.titleLabel.font = [UIFont fontWithName:#"icomoon" size:16.0];
[btn3 setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[btn3 setTitle:#"\ue001" forState:UIControlStateNormal];
btn3.tag = (indexPath.section +1)*20000;
[cell.contentView addSubview:btn3];
btn3.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[btn3 addTarget:self
action:#selector(otherAction:)
forControlEvents:UIControlEventTouchUpInside];
}
//Paginiation
if (indexPath.section == [dataArray count]-4 && indexPath.row == 1) {
[self loadNextPage];
}
return cell;
}
}
The reason you are seeing an image from another cell is that for efficiency's sake, table cells are reused. To get around this problem, set your image to nil after you dequeue the reusable cell in tableView:cellForRowAtIndexPath:.
First, you shouldn't be doing all of that stuff in cellForRowAtIndexPath.
You should subclass UITableViewCell and layout the cell in it's own class.
Cell for row at indexPath should load the cell and populate data. Not layout loads of controls.
Second, once you've done this you can call...
- (void)prepareForReuse
{
self.imageView.image = nil;
}
This will clear the imageView on dequeue of the cell so that if there is a delay loading hte image then you only see a blank imageView rather than the image that was in there previously.
In my app, I used a splitView. There are 3 different tables.
When I select any row from 1st Table, the display in the detail view & row remains selected in Left side menu. However, when I select any row from 2nd or 3rd Table, the row is just highlighted with blue color & quickly disappear the Selected blue (i.e. it does not remain Highlighted).
Help me solve this problem.
My code as follow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(tableView == tbl_class)
{
btnEdit1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btnEdit1 setFrame:CGRectMake(220, 15, 20, 20)];
[btnEdit1 addTarget:self action:#selector(btnEditPressed:) forControlEvents:UIControlEventTouchUpInside];
[btnEdit1 setImage:[UIImage imageNamed:#"edit-3-black.png"] forState:UIControlStateNormal];
UIButton *btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDelete setFrame:CGRectMake(260, 15, 20, 20)];
[btnDelete addTarget:self action:#selector(btnDelete:) forControlEvents:UIControlEventTouchUpInside];
[btnDelete setImage:[UIImage imageNamed:#"recycle-bin2.png"] forState:UIControlStateNormal];
[btnEdit1 setTag:indexPath.row];
[btnDelete setTag:indexPath.row];
cell.textLabel.text=[NSString stringWithFormat:#"%#",[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_name"]];
if(! isEditing)
{
[cell.contentView addSubview:btnEdit1];
[cell.contentView addSubview:btnDelete];
}
}
if(tableView==tbl_assessment)
{
if (classNames.count > 0)
{
[btnAddAssesst setHidden:NO];
}
else
{
[btnAddAssesst setHidden:YES];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[[assessment_list objectAtIndex:indexPath.row]valueForKey:#"assessment_name"]];
}
if (tableView==tbl3)
{
cell.textLabel.text=[arr_result objectAtIndex:indexPath.row];
}
cell.textLabel.font=[UIFont fontWithName:#"Trebuchet MS" size:17.0f];
cell.textLabel.textColor=[UIColor grayColor];
return cell;
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
*/
//NSUInteger row = indexPath.row;
if (aTableView==tbl_class)
{
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
self.secondDetailViewController=[[[Class_Vice_ViewController alloc]init]autorelease];
[viewControllerArray addObject:self.secondDetailViewController];
self.appDelegate.splitViewController.delegate = self.secondDetailViewController;
[[NSUserDefaults standardUserDefaults]setInteger:[[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_id"]intValue] forKey:#"psel_class"];
[self databaseOpen];
assessment_list=[[NSMutableArray alloc]init];
NSString *qq=[NSString stringWithFormat:#"select * from Assessment where class_id=%d",[[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_id"]intValue]];
assessment_list=[[database executeQuery:qq]mutableCopy];
[database close];
if (classNames.count > 0)
{
[btnAddAssesst setHidden:NO];
}
else
{
[btnAddAssesst setHidden:YES];
}
if (!assessment_list.count==0) {
[tbl_assessment setHidden:NO];
[btnDelete setHidden:NO];
[tbl_assessment reloadData];
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
[tbl_assessment reloadData];
}
else if (aTableView==tbl_assessment)
{
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
self.thirdDetailViewController=[[[GameAssessment alloc]init]autorelease];
[viewControllerArray addObject:self.thirdDetailViewController];
self.appDelegate.splitViewController.delegate = self.thirdDetailViewController;
[[NSUserDefaults standardUserDefaults]setInteger:[[[assessment_list objectAtIndex:indexPath.row]valueForKey:#"assessment_id"]intValue] forKey:#"ASSESSMENT_ID"];
[self databaseOpen];
assessment_list=[[NSMutableArray alloc]init];
NSString *qq=[NSString stringWithFormat:#"select * from Assessment where class_id=%d",[[NSUserDefaults standardUserDefaults]integerForKey:#"psel_class"]];
assessment_list=[[database executeQuery:qq]mutableCopy];
[database close];
if (!assessment_list.count==0) {
[tbl_assessment setHidden:NO];
[tbl_assessment reloadData];
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
}
else {
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
if (indexPath.row==0) {
self.fifthViewController=[[[ResultStudent_vice alloc]init]autorelease];
[viewControllerArray addObject:self.fifthViewController];
self.appDelegate.splitViewController.delegate = self.fifthViewController;
}
if (indexPath.row==1) {
self.fourthDetailViewController=[[[ResultClass_vice alloc]init]autorelease];
[viewControllerArray addObject:self.fourthDetailViewController];
self.appDelegate.splitViewController.delegate = self.fourthDetailViewController;
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
}
}
Two things to do to keep the row as selected
-deselectRowAtIndexpath should not be there in didselectRowAtIndexpath
Keep an NSMutableArray of NSIndexpath for storing the selected value .When a row is selected add it to array and in the -cellForRowAtIndexpath method check the indexpath is there in cell and if it is there make [tablecell setSelected:YES]; otherwise NO