I'm getting correct data after loading the page as shown in this screen
getting correct data even after performing search like this image
but after search is cancelled im getting wrong data (label should be ph:+ and Fax:+ but its displaying both as Fax:+ like this
with this code
#implementation Staffdir
#synthesize tableview,filteredContentList,searchBar1;
- (void)viewDidLoad {
searchBar1.delegate = self;
__block StaffDirectoryModel*staffdirectorymodel;
NSURL *url = [NSURL URLWithString:#"http://dev.devobal.com/GetData.aspx?Query=select%20*%20from%20tb_RHP_Staff_Directory"];
_staffdirarr=[[NSMutableArray alloc]init];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
[[[NSURLSession sharedSession]dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableArray *jsonarr=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI
for(int i=0;i<jsonarr.count;i++){
staffdirectorymodel=[[StaffDirectoryModel alloc]init];
staffdirectorymodel.name =[[jsonarr objectAtIndex:i]objectForKey:#"Name"];
staffdirectorymodel.occupation=[[jsonarr objectAtIndex:i]objectForKey:#"Job_Title"];
staffdirectorymodel.phonelabel =[[jsonarr objectAtIndex:i]objectForKey:#"Phone"];
staffdirectorymodel.faxlabel =[[jsonarr objectAtIndex:i]objectForKey:#"Fax_Number"];
staffdirectorymodel.department =[[jsonarr objectAtIndex:i]objectForKey:#"Department"];
[_staffdirarr addObject:staffdirectorymodel];
staffdirectorymodel=nil;
}
[tableview reloadData];
});
}]resume];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
// return 1;
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (isSearching) {
return [searchResults count];
}else{
return _staffdirarr.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellidentifer = #"cell";
StaffDirectoryModel*staffdirectorymodel=[[StaffDirectoryModel alloc]init];
Staffcustom *cell= [tableView dequeueReusableCellWithIdentifier:cellidentifer];
if (cell == nil) {
cell = [[Staffcustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifer];
}
[cell.fxlabel setHidden:NO];
[cell.faxnumlabel setHidden:NO];
if (isSearching) {
staffdirectorymodel=[searchResults objectAtIndex:indexPath.row];
cell.namelabel.text = staffdirectorymodel.name;
cell.occupationlabel.text = staffdirectorymodel.occupation;
NSString*tempph=staffdirectorymodel.phonelabel;
NSString*tempfax=staffdirectorymodel.faxlabel;
if(tempph.length!=0)
{
cell.phonelabel.text = staffdirectorymodel.phonelabel;
}
else{
cell.phlabel.text=#"Fax: +";
cell.phonelabel.text = staffdirectorymodel.faxlabel;
[cell.fxlabel setHidden:YES];
[cell.faxnumlabel setHidden:YES];
}
if(tempfax.length==0)
{
[cell.faxnumlabel setHidden:YES];
[cell.fxlabel setHidden:YES];
}
if([tempph length]!=0 &&[tempfax length]!=0){
cell.faxnumlabel.text = staffdirectorymodel.faxlabel;
}
cell.Depart.text = staffdirectorymodel.department;
}
else{
staffdirectorymodel=[_staffdirarr objectAtIndex:indexPath.row];
cell.namelabel.text = staffdirectorymodel.name;
cell.occupationlabel.text = staffdirectorymodel.occupation;
NSString*tempph=staffdirectorymodel.phonelabel;
NSString*tempfax=staffdirectorymodel.faxlabel;
if(tempph.length!=0)
{
cell.phonelabel.text = staffdirectorymodel.phonelabel;
}
else{
cell.phlabel.text=#"Fax: +";
cell.phonelabel.text = staffdirectorymodel.faxlabel;
[cell.fxlabel setHidden:YES];
[cell.faxnumlabel setHidden:YES];
}
if(tempfax.length==0)
{
[cell.faxnumlabel setHidden:YES];
[cell.fxlabel setHidden:YES];
}
if([tempph length]!=0 &&[tempfax length]!=0){
cell.faxnumlabel.text = staffdirectorymodel.faxlabel;
}
cell.Depart.text = staffdirectorymodel.department;
}
cell.namelabel.textColor = [UIColor blueColor];
cell.occupationlabel.textColor=[UIColor colorWithRed:0.5 green:0.0 blue:1 alpha:1.0];
UIView * additionalSeparator = [[UIView alloc] initWithFrame:CGRectMake(0,cell.frame.size.height-1,cell.frame.size.width,0.1)];
additionalSeparator.backgroundColor = [UIColor blueColor];
[cell addSubview:additionalSeparator];
return cell;
}
//- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
// isSearching = YES;
//}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)searchText
{
//[filteredContentList removeAllObjects];
if(searchText.length!=0){
isSearching=YES;
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"name contains[c] %#",
searchText];
searchResults=(NSMutableArray *)[_staffdirarr filteredArrayUsingPredicate:resultPredicate];
[tableview reloadData];
}
else{
isSearching=NO;
[tableview reloadData];
}
//
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
isSearching=YES;
[tableview reloadData];}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
isSearching=NO;
[tableview reloadData];}
and
staffdirectory model class
#interface StaffDirectoryModel : NSObject
#property (nonatomic,retain) NSString*name;
#property (nonatomic,retain) NSString*occupation;
#property (nonatomic,retain) NSString*phlabel;
#property (nonatomic,retain) NSString*phonelabel;
#property (nonatomic,retain) NSString*fxlabel;
#property (nonatomic,retain) NSString*faxlabel;
#property (nonatomic,retain) NSString*department;
staffcustom.h
#interface Staffcustom : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *fxlabel;
#property (weak, nonatomic) IBOutlet UILabel *namelabel;
#property (weak, nonatomic) IBOutlet UILabel *occupationlabel;
#property (weak, nonatomic) IBOutlet UILabel *phlabel;
#property (weak, nonatomic) IBOutlet UILabel *faxlabel;
#property (weak, nonatomic) IBOutlet UILabel *phonelabel;
#property (weak, nonatomic) IBOutlet UILabel *faxnumlabel;
#property (nonatomic,retain) IBOutlet UILabel *Depart;
#end
Related
I'm developing an app in Xcode in Objective-C.
The app has a TableView with an array of restaurants. My problem is that when I try to use the SearchBar I use the Title (name of the restaurant as a filter) but when I show the rows after the filter search, only the Title is right. The other label and the image in the cell is wrong (it shows me the correct title but the image and the other label (description label) is the same as the first row in the original tableview).
I have to change my cellForRowAtIndexPath method but I don't now how to change it.
This is TableViewController called MainTableViewController.h
#import <UIKit/UIKit.h>
#interface MainTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
#property (weak, nonatomic) IBOutlet UIBarButtonItem *barButton;
//#property (nonatomic, strong) NSArray *Images;
//#property (nonatomic, strong) NSArray *Description;
//#property (nonatomic, strong) NSArray *Title;
#property (nonatomic, strong) NSMutableArray *Title;
#property (nonatomic, strong) NSMutableArray *Images;
#property (nonatomic, strong) NSMutableArray *Description;
#property (nonatomic, strong) NSMutableArray *filteredRest;
#property BOOL isFiltered;
#property (strong, nonatomic) IBOutlet UITableView *RestTableView;
#property (strong, nonatomic) IBOutlet UITableView *mySearchBar;
#end
This is my MainTableViewController.c
#import "MainTableViewController.h"
#import "SWRevealViewController.h"
#import "RestTableViewCell.h"
#import "RestViewController.h"
#interface MainTableViewController ()
#end
#implementation MainTableViewController
#synthesize mySearchBar, filteredRest, isFiltered;
- (void)viewDidLoad {
[super viewDidLoad];
_barButton.target = self.revealViewController;
_barButton.action = #selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
[self.navigationItem setTitle:#"MadEat"]; /*Cambia el titulo del navigation controller*/
[self.navigationController.navigationBar setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}]; /*Cambia el color de las letras del navigation controller bar del menu principal*/
[self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:27/255.0f green:101/255.0f blue:163/255.0f alpha:1.0f]];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; /*Cambia el color del boton de la izquierda*/
self.RestTableView.tableFooterView = [[UIView alloc] init]; /*Esta linea hace que en la tabla solo aparezcan el numero de filas que tienes establecidas, es decir, que las vacias no aparezcan*/
/*Alerta que se muestra solo la primera vez. Está desactivada*/
if (![#"1" isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:#"alert"]]) {
[[NSUserDefaults standardUserDefaults] setValue:#"1" forKey:#"alert"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Terms of use" message:#"The brands mentioned have no relationship with MadEat and the app has no any liability on that content." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"Accept" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
}
_Title = #[#"80 Grados",
#"90 Grados",
#"B&B Babel",
#"Babelia",
#"Bacira",
#"Bar Galleta",
#"Bar Tomate",
#"Barra Atlantica",
#"BaRRa de Pintxos",
#"BaRRa de Pintxos",];
_Description = #[#"Barrio Malasaña",
#"Barrio Retiro",
#"Barrio Chueca",
#"Barrio de Salamanca",
#"Barrio Chamberí",
#"Barrio Malasaña",
#"Barrio Chamberí",
#"Barrio Malasaña",
#"Barrio del Pilar",
#"Barrio Retiro",];
_Images = #[#"80_grados.png",
#"90_grados",
#"babel.png",
#"babelia.png",
#"bacira.png",
#"bar_galleta.png",
#"bar_tomate.png",
#"barra_atlantica.png",
#"barra_de_pintxos.png",
#"barra_de_pintxos.png",];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//return _Title.count;
if (isFiltered == YES) {
return filteredRest.count;
} else {
return _Title.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
RestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row];
} else {
int row = [indexPath row];
cell.TitleLabel.text = _Title[row];
cell.DescriptionLabel.text = _Description[row];
cell.RestImage.image = [UIImage imageNamed:_Images[row]];
}
cell.RestImage.layer.cornerRadius = 6;
cell.RestImage.clipsToBounds = YES;
cell.RestImage.layer.borderWidth = 1;
return cell;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/*Cambia el nombre del boton de la izquierda sin afectar al titulo del navigation controller*/
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: NSLocalizedString (#"Back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];
if ([[segue identifier] isEqualToString:#"ShowDetails"]){
RestViewController *restviewcontroller = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
int row = [myIndexPath row];
restviewcontroller.DetailModal = #[_Title[row],_Description[row],_Images[row]];
}
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
filteredRest = [[NSMutableArray alloc] init];
for (NSString * restTitle in _Title) {
NSRange restTitleRange = [restTitle rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (restTitleRange.location != NSNotFound) {
[filteredRest addObject:restTitle];
}
}
for (NSString * restDescription in _Description) {
NSRange restDescriptionRange = [restDescription rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (restDescriptionRange.location != NSNotFound) {
//[filteredRest addObject:restDescription];
}
}
for (NSString * restImages in _Images) {
NSRange restImagesRange = [restImages rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (restImagesRange.location != NSNotFound) {
//[filteredRest addObject:restImages];
}
}
//Reload our table view
[_RestTableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[mySearchBar resignFirstResponder];
}
#end
Finally, this is my TableViewCell.h called RestTableViewCell.h
#import <UIKit/UIKit.h>
#interface RestTableViewCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UILabel *TitleLabel;
#property (strong, nonatomic) IBOutlet UILabel *DescriptionLabel;
#property (strong, nonatomic) IBOutlet UIImageView *RestImage;
#end
This is my problem graphically:
Obviously, you just apply the filter condition to the Title array, and not filtering the Images and Description array.
So you need to two more NSMutableArray to hold the filtering results for Images and Description.
But I recommend you to build a new Model for your results. Sample code for your reference:
Model layer: Restaurant.h
#interface Restaurant : NSObject
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *desc;
#property (nonatomic, copy) NSString *image;
- (instancetype)init:(NSString *)title descripiton:(NSString *)description image:(NSString *)image;
#end
Restaurant.m
#implementation Restaurant
- (instancetype)init:(NSString *)title descripiton:(NSString *)description image:(NSString *)image {
self = [super init];
if (self != nil) {
self.title = title;
self.desc = description;
self.image = image;
}
return self;
}
#end
RestViewController.h
#interface RestViewController : UIViewController
#property (nonatomic, strong) Restaurant *DetailModal;
#end
MainTableViewController.m
#interface MainTableViewController ()
#property (nonatomic, strong) NSArray<Restaurant *> *originData;
#property (nonatomic, strong) NSMutableArray<Restaurant *> *filteredRest;
#property (nonatomic, assign) Boolean isFiltered;
#end
#implementation MainTableViewController
#synthesize mySearchBar, filteredRest, isFiltered, originData;
- (void)viewDidLoad {
[super viewDidLoad];
originData = #[
[[Restaurant alloc] init:#"80 Grados" descripiton:#"Barrio Malasaña" image:#"80_grados.png"],
[[Restaurant alloc] init:#"90 Grados" descripiton:#"Barrio Retiro" image:#"90_grados"]
];
filteredRest = [NSMutableArray new];
isFiltered = NO;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//return _Title.count;
if (isFiltered == YES) {
return filteredRest.count;
} else {
return originData.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
RestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [filteredRest objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[filteredRest objectAtIndex:indexPath.row].image];
} else {
cell.TitleLabel.text = [originData objectAtIndex:indexPath.row].title;
cell.DescriptionLabel.text = [originData objectAtIndex:indexPath.row].desc;
cell.RestImage.image = [UIImage imageNamed:[originData objectAtIndex:indexPath.row].image];
}
cell.RestImage.layer.cornerRadius = 6;
cell.RestImage.clipsToBounds = YES;
cell.RestImage.layer.borderWidth = 1;
return cell;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/*Cambia el nombre del boton de la izquierda sin afectar al titulo del navigation controller*/
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: NSLocalizedString (#"Back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];
if ([[segue identifier] isEqualToString:#"ShowDetails"]){
RestViewController *restviewcontroller = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
if (isFiltered) {
restviewcontroller.DetailModal = filteredRest[myIndexPath.row];
} else {
restviewcontroller.DetailModal = originData[myIndexPath.row];
}
}
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchText.length == 0) {
//Set our boolean flag
isFiltered = NO;
} else {
//Set our boolean flag
isFiltered = YES;
}
//Alloc and init our filteredData
filteredRest = [[NSMutableArray alloc] init];
for (Restaurant *item in originData) {
if ([item.title containsString:searchText]) {
[filteredRest addObject:item];
}
}
//Reload our table view
[self.tableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[mySearchBar resignFirstResponder];
}
#end
With building a new model object for your information is very efficient, so you don't need to apply there filter to three array, you just need to search once, and results will be kept kept in one array.
PS: One more tips for your coding style, naming the variable, object instance with starting lowercase, and naming the class with starting uppercase is best practise when writing OC codes. e.g., TitleLabel should rename to titleLabel, etc...
Here you are filtering cell and reusing them.
You are just replacing text. You need to replace the image and data as well.
if (isFiltered == YES) {
cell.TitleLabel.text = [filteredRest objectAtIndex:indexPath.row];
} else {
int row = [indexPath row];
cell.TitleLabel.text = _Title[row];
cell.DescriptionLabel.text = _Description[row];
cell.RestImage.image = [UIImage imageNamed:_Images[row]];
}
I am not sure but I think you have not clearly understood concept of reusable cell. You will be reusing cell which are not in the view what that means is iOS framework will give you one of the already used cell so that it doesnt have to recreate cell everytime in your case thats first cell 80Grados.
So, after you receive that cell, you replace the title but leave all other content alone. That is why you see old content with new Title Label.
What you need to do here is create a wrapper class, which will have three properties text, description and imagefile name.
#class Restaurant
#property NSString *title;
#property NString *description;
#property NSString *image;
#end
Combine your logic with this rather than treating all data as separate array. That will be extremely easy to maintain. In future you can easily fill that class with data coming from server, user entered or any otherway. Handling data in 3 different array is not very sustainable model.
So create wrapper class, fill data by creating NSMutableArray/NSMutableDictionary. Rather than putting title, fill entire wrapper object.
[filteredRest addObject: restaurantObj];
And change your code this way
Restaurant *r;
if (isFiltered == YES) {
r = [self.filteredRest objectAtIndex:indexPath.row];
} else {
r = [self.restaurantList objectAtIndex:indexPath.row]];
}
cell.TitleLabel.text = r.title;
cell.DescriptionLabel.text = r.description;
cell.RestImage.image = [UIImage imageNamed:r.image];
Let me know if any of the ideas are not clear. This is just a prototype, you will have to change your code in multiple places but would highly recommend making these changes sooner than later.
I have project with normal cell and working success but I want to change it with custom cell I added Cell.h and Cell.m files into my project and I need to integrate custom cell to my working cell. And last I want to show detail view title description and image (I added title codes working) My codes under
Cell.h
#import <UIKit/UIKit.h>
#interface Cell : UITableViewCell
#property (nonatomic, weak) IBOutlet UIImageView *imaj;
#property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#end
Cell.m
#import "Cell.h"
#implementation Cell
#synthesize imaj = _imaj;
#synthesize descriptionLabel = _descriptionLabel;
#synthesize titleLabel = _titleLabel;
#end
ViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "Cell.h"
static NSString *const kConsumerKey = #"a1SNULSPtp4eLQTsTXKKSgXkYB5H4CMFXmleFvqE";
#interface MasterViewController () <UISearchBarDelegate, UISearchDisplayDelegate,MBProgressHUDDelegate>{
MBProgressHUD *HUD;
}
#property (nonatomic, assign) NSInteger currentPage;
#property (nonatomic, assign) NSInteger totalPages;
#property (nonatomic, assign) NSInteger totalItems;
#property (nonatomic, assign) NSInteger maxPages;
#property (nonatomic, strong) NSMutableArray *activePhotos;
#property (strong, nonatomic) NSMutableArray *staticDataSource;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation MasterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.activePhotos = [[NSMutableArray alloc] init];
self.searchResults = [[NSMutableArray alloc] init];
self.staticDataSource = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadPhotos:self.currentPage];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// if (self.currentPage == self.maxPages
// || self.currentPage == self.totalPages
// || self.currentPage == self.totalPages
// || self.totalItems == self.photos.count) {
// return self.photos.count;
// } else if (self.tableView == self.searchDisplayController.searchResultsTableView){
// return [self.searchResults count];
//
// }
// return self.photos.count + 1;
return self.activePhotos.count + 1;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.currentPage != self.maxPages && indexPath.row == [self.staticDataSource count] - 1 ) {
[self loadPhotos:++self.currentPage];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == [self.activePhotos count]) {
cell = [self.tableView dequeueReusableCellWithIdentifier:#"LoadingCell" forIndexPath:indexPath];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = #"Loading";
[HUD showWhileExecuting:#selector(myTask) onTarget:self withObject:nil animated:YES];
} else {
NSDictionary *photoItem = self.activePhotos[indexPath.row];
cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// cell.textLabel.text = [self.searchResults[indexPath.row] valueForKey:#"name"];
// } else {
// NSDictionary *photoItem = self.photos[indexPath.row];
cell.textLabel.text = [photoItem objectForKey:#"name"];
if (![[photoItem objectForKey:#"description"] isEqual:[NSNull null]]) {
cell.detailTextLabel.text = [photoItem objectForKey:#"description"];
}
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:[photoItem objectForKey:#"image_url"] ] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (error) {
NSLog(#"Error occured : %#", [error description]);
}
}];
}
// NSLog(#"%#",self.searchResults);
return cell;
}
- (void)myTask {
// Do something usefull in here instead of sleeping ...
sleep(1.5);
}
#pragma mark UISearchDisplay delegate
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
// [self.searchResults removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF.name contains[c] %#", searchText];
self.activePhotos = [NSMutableArray arrayWithArray:[self.staticDataSource filteredArrayUsingPredicate:resultPredicate]];
//[self.tableData filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (void)loadPhotos:(NSInteger)page
{
NSString *apiURL = [NSString stringWithFormat:#"https://api.500px.com/v1/photos?feature=editors&page=%ld&consumer_key=%#",(long)page,kConsumerKey];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:apiURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *jsonError = nil;
NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",jsonObject);
[self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:#"photos"]];
self.currentPage = [[jsonObject objectForKey:#"current_page"] integerValue];
self.totalPages = [[jsonObject objectForKey:#"total_pages"] integerValue];
self.totalItems = [[jsonObject objectForKey:#"total_items"] integerValue];
self.activePhotos = self.staticDataSource;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}] resume];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DetailViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.StoreList = [self.activePhotos objectAtIndex:indexPath.row];
}
#end
Also I uploaded working project here
http://www.filedropper.com/needcustomcell
In your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Cell *cell;
// rest of your code
}
that would do it. You have used UITableViewCell you need to replace ot with your custom cell class.
When a user taps a cell, I want itemURL to be set to that cells "Item URL" property. Once it does this, it should then send over the itemURL in prepareForSegue over to WebViewController, as I've attempted to do. When I have WebViewController NSLog the itemURL property however, it comes up as null. How can I make sure the value is sent over properly?
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#import "WebViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#property (strong, nonatomic) NSString *searchTerm;
#property (strong, nonatomic) NSURL *itemURL;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
_matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _matchCenterArray.count;
}
//the part where i setup sections and the deleting of said sections
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 21.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
headerView.backgroundColor = [UIColor lightGrayColor];
_searchTerm = [[[[_matchCenterArray objectAtIndex:section] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
headerLabel.text = [NSString stringWithFormat:#"%#", _searchTerm];
headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
headerLabel.textColor = [UIColor whiteColor];
headerLabel.backgroundColor = [UIColor lightGrayColor];
[headerView addSubview:headerLabel];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.tag = section;
deleteButton.frame = CGRectMake(300, 2, 17, 17);
[deleteButton setImage:[UIImage imageNamed:#"xbutton.png"] forState:UIControlStateNormal];
[deleteButton addTarget:self action:#selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[headerView addSubview:deleteButton];
return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 65;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
// NSLog(#"The url is: '%#'", itemURL);
[self performSegueWithIdentifier:#"WebViewSegue" sender:self];
}
- (void)deleteButtonPressed:(id)sender
{
// links button
UIButton *deleteButton = (UIButton *)sender;
// Define the sections title
NSString *sectionName = _searchTerm = [[[[_matchCenterArray objectAtIndex:deleteButton.tag] objectForKey:#"Top 3"] objectAtIndex:3]objectForKey:#"Search Term"];
// Run delete function with respective section header as parameter
[PFCloud callFunctionInBackground:#"deleteFromMatchCenter"
withParameters:
#{#"searchTerm": sectionName,}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
[PFCloud callFunctionInBackground:#"MatchCenter"
withParameters:#{
#"test": #"Hi",
}
block:^(NSArray *result, NSError *error) {
if (!error) {
_matchCenterArray = result;
[_matchCenter reloadData];
NSLog(#"Result: '%#'", result);
}
}];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
WebViewController *controller = (WebViewController *) segue.destinationViewController;
controller.itemURL = self.itemURL;
}
#end
WebViewController.h:
#import <UIKit/UIKit.h>
#import "MatchCenterViewController.h"
#interface WebViewController : UIViewController <UIWebViewDelegate>
#property (strong, nonatomic) NSURL *itemURL;
#property (weak, nonatomic) IBOutlet UIWebView *myWebView;
#end
WebViewController.m:
#import "WebViewController.h"
#interface WebViewController ()
#end
#implementation WebViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"The url is: '%#'", _itemURL);
// _myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
// _myWebView.delegate=self;
// [self.view addSubview:_myWebView];
self.myWebView.delegate = self;
//////////
NSURLRequest *request = [NSURLRequest requestWithURL:_itemURL];
//4
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//5
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil) [self.myWebView loadRequest:request];
else if (error != nil) NSLog(#"Error: %#", error);
}];
[self.myWebView setScalesPageToFit:YES];
//////
//[self.myWebView loadRequest:request];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
In your didSelectRowForIndexPath: instead of
NSURL *itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
use
self.itemURL = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row][#"Item URL"];
I'm trying to push the image from selected row to a detailed viewController. This is what I tried the latest. I also tried to get the PFFile from an PFImageView but unsuccessful.
#import "ExploreViewController.h"
#import "DetailExploreViewController.h"
#interface ExploreViewController ()
#property (strong, nonatomic) PFGeoPoint *userLocation;
#property (weak, nonatomic) UIImage *imagine;
#property (weak, nonatomic) NSString *discovery;
#end
- (PFQuery *) queryForTable
{
if (!self.userLocation) {
return nil;
}
PFQuery *query = [PFQuery queryWithClassName:#"HomePopulation"];
[query whereKey:#"geopoint" nearGeoPoint:self.userLocation withinKilometers:15];
query.limit = 25;
//[self getLocation];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleIdentifier = #"ExploreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = [object objectForKey:#"discovery"];
PFFile *getImage = [object objectForKey:#"imageFile"];
[getImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
cell.imageView.image = [UIImage imageWithData:data];
NSLog(#"hojla: %#", cell.imageView.image);
} else {
cell.imageView.image = [UIImage imageNamed:#"1bar.jpg"];
}
}];
return cell;
}
- (void)tableView:(UITableView *)tableViewer didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableViewer cellForRowAtIndexPath:indexPath];
self.discovery = cell.textLabel.text;
NSLog(#"the text: %#", self.discovery);
self.imagine = cell.imageView.image;
NSLog(#"ajde: %#", self.imagine);
}
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"toDetail"]) {
DetailExploreViewController *destViewController = segue.destinationViewController;
destViewController.theImage = self.imagine;
destViewController.theString = self.discovery;
}
}
DetailExploreViewController.h
#import <UIKit/UIKit.h>
#interface DetailExploreViewController : UIViewController
#property (strong, nonatomic) NSString *theString;
#property (strong, nonatomic) UIImage *theImage;
#end
DetailExploreViewController.m
#import "DetailExploreViewController.h"
#interface DetailExploreViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *theImageView;
#property (weak, nonatomic) IBOutlet UILabel *theLabel;
#end
#implementation DetailExploreViewController
#synthesize theString, theLabel, theImageView, theImage;
- (void)viewDidLoad
{
[super viewDidLoad];
theLabel.text = theString;
theImageView.image = theImage;
}
In your cellForRowAtIndexPath you are creating a new UIImageView to contain your image, but not doing anything with it. Once you have the image you can just assign it to the cell's imageView.image property -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleIdentifier = #"ExploreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = [object objectForKey:#"discovery"];
PFFile *getImage = [object objectForKey:#"imageFile"];
[getImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
cell.imageView.image = [UIImage imageWithData:data];
NSLog(#"hojla: %#", cell.imageView.image);
}
else {
//TODO - Put some placeholder/"not found" image into cell.imageView.image
}
}];
return cell;
}
Then, in your didSelectRowAtIndexPath -
- (void)tableView:(UITableView *)tableViewer didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableViewer cellForRowAtIndexPath:indexPath];
UILabel *label = cell.textLabel
NSLog(#"the text: %#", label.text);
UIImageView *img = cell.imageView;
NSLog(#"ajde: %#", img.image);
}
Try sending a message to the detail controller instead of using the dot syntax like so:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"toDetail"]) {
DetailExploreViewController *destViewController = segue.destinationViewController;
[destViewController setTheImage:self.theImage];
[destViewController setTheString:self.theString];
}
}
In the detail controller implementation file , I would set up the detail view image in the viewWillAppear method instead like so:
-(void)viewWillAppear:(BOOL)animated{
theLabel.text = theString;
theImageView.image = theImage;
}
This works for me.
Thanks to #Paulw11's advice I made it happen like this:
ExploreViewController.m
- (PFQuery *) queryForTable {
if (!self.userLocation) {
return nil;
}
PFQuery *query = [PFQuery queryWithClassName:#"HomePopulation"];
[query whereKey:#"geopoint" nearGeoPoint:self.userLocation withinKilometers:15];
query.limit = 25;
// Calling getData to populate the array at the same time as the tableView is being loaded
[self getData];
return query;
}
//Retrieving objects from Parse and adding them in a NSMutableArray
- (void)getData {
PFQuery *query = [PFQuery queryWithClassName:#"HomePopulation"];
[query whereKey:#"geopoint" nearGeoPoint:self.userLocation withinKilometers:15];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (PFObject *object in objects) {
Detailish *detail = [Detailish new]; // Detailish is a class for the array objects
detail.discovery = [object objectForKey:#"discovery"];
PFFile *getImage = [object objectForKey:#"imageFile"];
[getImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
detail.imagine = [UIImage imageWithData:data];
NSLog(#"Detail imagine: %#", detail.imagine);
}
}];
detail.location = [object objectForKey:#"location"];
[forDetail addObject:detail];
}
}
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject
*)object {
static NSString *simpleIdentifier = #"ExploreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdentifier];
}
cell.textLabel.text = [object objectForKey:#"discovery"];
return cell; }
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"toDetail"]) {
DetailExploreViewController *destViewController = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSLog(#"Halo ej: %#", [forDetail objectAtIndex:indexPath.row]);
destViewController.hump = [forDetail objectAtIndex:indexPath.row];
Detailish *details = [forDetail objectAtIndex:indexPath.row];
NSLog(#"discovery: %#", details.discovery);
NSLog(#"image: %#", details.imagine);
} }
DetailExploreViewController.h
#import <UIKit/UIKit.h>
#import "Detailish.h"
#interface DetailExploreViewController : UIViewController
#property (strong, nonatomic) Detailish *hump;
#end
DetailExploreViewController.m
#import "DetailExploreViewController.h"
#interface DetailExploreViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *theImageView;
#property (weak, nonatomic) IBOutlet UILabel *theLabel;
#end
#implementation DetailExploreViewController
#synthesize theLabel, theImageView;
- (void) viewWillAppear:(BOOL)animated
{
theLabel.text = self.hump.discovery;
theImageView.image = self.hump.imagine;
}
Detailish.h
#import <Foundation/Foundation.h>
#interface Detailish : NSObject
#property (strong, nonatomic) NSString *discovery;
#property (strong, nonatomic) NSString *location;
#property (strong, nonatomic) UIImage *imagine;
#end
Detailish.m
#import "Detailish.h"
#implementation Detailish
#synthesize discovery, location, imagine;
#end
I'm seeing a gradual build up of memory that I think might be a retain cycle.
When does this happen: Click on a custom cell that expands and injects a nib with 3 buttons into the expanded area. Clicking the cell again closes the cell, shrinks the cell's tablerow height, rotates an open indicator and removes the previously injected nib.
If I open and close the cell multiple times I see the memory gradually building up.
Any ideas what might be causing this would be greatly appreciated.
Sorry I don't have enough reputation to post photos.
Build up:
Example of retained objects(mostly Animation related):
EDIT: Using ARC and on iOS 6
MasterViewController - TableView Functions
#pragma mark - UITABLEVIEW
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.topicsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier2 = #"SRCollapsibleCellClosed";
SRCollapsibleCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
cell = [[SRCollapsibleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
}
SRTopic *topic = [self.topicsArray objectAtIndex:indexPath.row];
[cell updateWithTopic:topic];
if([self isCellOpen:indexPath]){
CGAffineTransform transformation = CGAffineTransformMakeRotation(M_PI/2);
cell.arrow.transform = transformation;
if(![self hasChoiceBox:cell]){
[self insertChoiceBox:cell atIndex:indexPath];
}
} else{
CGAffineTransform transformation = CGAffineTransformMakeRotation(0);
cell.arrow.transform = transformation;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if([self isCellOpen:indexPath]){
[self closeCellAtIndexPath:indexPath];
}
else{
NSIndexPath * openCell= self.openCellIndex;
NSIndexPath * newOpenCell= indexPath;
[self closeCellAtIndexPath:openCell];
[self openCellAtIndexPath:newOpenCell];
}
[tableView beginUpdates];
[tableView endUpdates];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
}
-(CGFloat)tableView: (UITableView*)tableView heightForRowAtIndexPath: (NSIndexPath*) indexPath {
if([indexPath isEqual:self.openCellIndex]){
return 217.0;
} else {
return 63.0;
}
}
-(void)rotateCellArrowAtIndexPath:(NSIndexPath*)indexPath willOpen:(bool)willOpen Animated:(bool)animated{
// Change Arrow orientation
SRCollapsibleCell *cell = (SRCollapsibleCell*) [self.topicsTableView cellForRowAtIndexPath:indexPath];
CGAffineTransform transformation;
if(willOpen){
transformation = CGAffineTransformMakeRotation(M_PI/2);
} else {
transformation = CGAffineTransformMakeRotation(0);
}
if(animated){
[UIView animateWithDuration:.2 delay:0 options:nil animations:^{
cell.arrow.transform = transformation;
} completion:nil];
}
else{
cell.arrow.transform = transformation;
}
}
-(BOOL)isCellOpen:(NSIndexPath *)indexPath{
return [indexPath isEqual:self.openCellIndex];
}
-(void)closeCellAtIndexPath:(NSIndexPath*)indexPath{
//NSLog(#"Cell closing");
[self rotateCellArrowAtIndexPath:indexPath willOpen:NO Animated:YES];
[self removeSRChoiceBoxFromCellAtIndexPath:indexPath];
self.openCellIndex = nil;
}
-(void)openCellAtIndexPath:(NSIndexPath*)indexPath{
[self rotateCellArrowAtIndexPath:indexPath willOpen:YES Animated:YES];
SRCollapsibleCell *cell = (SRCollapsibleCell*)[self.topicsTableView cellForRowAtIndexPath:indexPath];
[self insertChoiceBox:cell atIndex:indexPath];
self.openCellIndex = indexPath;
}
-(void)removeSRChoiceBoxFromCellAtIndexPath:(NSIndexPath *)indexPath{
SRCollapsibleCell *cell = (SRCollapsibleCell*) [self.topicsTableView cellForRowAtIndexPath:indexPath];
for(id subview in cell.SRCollapsibleCellContent.subviews){
if([subview isKindOfClass:[SRChoiceBox class]]){
SRChoiceBox *tempBox = subview;
[tempBox removeFromSuperview];
tempBox.delegate = nil;
tempBox = nil;
}
}
}
-(void)insertChoiceBox: (SRCollapsibleCell *)cell atIndex:(NSIndexPath *) indexPath
{
//SRChoiceBox *newBox = [[SRChoiceBox alloc] initWithFrame:CGRectMake(0, 0, 310, 141)];
SRChoiceBox *newBox = [[SRChoiceBox alloc] init];
SRTopic *topic = [self.topicsArray objectAtIndex:indexPath.row];
[newBox updateWithSRTopic:topic];
newBox.delegate = self;
[cell.SRCollapsibleCellContent addSubview:newBox];
cell = nil;
topic = nil;
newBox = nil;
}
-(bool)hasChoiceBox:(SRCollapsibleCell *)cell{
for(UIView *subview in cell.SRCollapsibleCellContent.subviews){
if([subview isKindOfClass:[SRChoiceBox class]]){
return true;
}
}
return false;
}
SRChoiceBox - UIView object that gets inserted into cell
//.h
#protocol SRChoiceBoxDelegate <NSObject>
-(void)positionWasChoosen: (NSString *)choice topicId: (NSNumber *)topicId;
#end
#interface SRChoiceBox : UIView
-(id) initWithLabel: (NSDictionary *)labels andTopicID: (NSNumber *)topicId andFrame:(CGRect)frame;
#property (nonatomic, weak) IBOutlet UIView *SRChoiceBox;
#property (nonatomic, strong) NSNumber *SRTopicId;
#property (nonatomic, weak) id<SRChoiceBoxDelegate> delegate;
#property (weak, nonatomic) IBOutlet UILabel *agreeCount;
#property (weak, nonatomic) IBOutlet UILabel *disagreeCount;
#property (weak, nonatomic) IBOutlet UILabel *observeCount;
-(IBAction)buttonPress:(id)sender;
-(void)updateWithSRTopic:(SRTopic *)topic;
....
//.m
-(id)init{
self = [super init];
if (self) {
UINib *nib = [UINib nibWithNibName:#"SRChoiceBox" bundle:nil];
NSArray *q = [nib instantiateWithOwner:self options:nil];
[self addSubview:q[0]];
}
return self;
}
-(void)updateWithSRTopic:(SRTopic *)topic
{
self.SRTopicId = topic.topicId;
self.agreeCount.text = [NSString stringWithFormat: #"%#",topic.agreeDebaters];
self.disagreeCount.text = [NSString stringWithFormat: #"%#",topic.disagreeDebaters];
self.observeCount.text = [NSString stringWithFormat: #"%#",topic.observers];
}
- (IBAction)buttonPress:(id) sender {
int tag = [sender tag];
switch (tag) {
case 0:
[self.delegate positionWasChoosen:#"agree" topicId:self.SRTopicId];
break;
case 1:
[self.delegate positionWasChoosen: #"disagree" topicId:self.SRTopicId];
break;
case 2:
[self.delegate positionWasChoosen: #"observe" topicId:self.SRTopicId];
break;
default:
break;
}
}
- (void)dealloc
{
self.SRChoiceBox =nil;
self.SRTopicId=nil;
self.delegate=nil;
self.agreeCount=nil;
self.disagreeCount=nil;
self.observeCount=nil;
//NSLog(#"choicebox deallocated: %#", self);
}
SRCollapsibleCell -- Reusable cell
//.h
#interface SRCollapsibleCell : UITableViewCell
#property (strong) NSNumber *topicId;
#property (strong) NSDictionary *topicStats;
#property (weak, nonatomic) IBOutlet UILabel *title;
#property (weak, nonatomic) IBOutlet UILabel *subtitle;
#property (weak, nonatomic) IBOutlet UILabel *agreeDebaters;
#property (weak, nonatomic) IBOutlet UILabel *disagreeDebaters;
#property (weak, nonatomic) IBOutlet UILabel *observers;
#property (weak, nonatomic) IBOutlet UIImageView *arrow;
#property (weak, nonatomic) IBOutlet UIView *SRCollapsibleCellContent;
//-(void)updateWithTopic:(NSDictionary *) stats;
-(void)formatTitle:(NSString *)title;
-(void)updateWithTopic: (SRTopic *)topic;
#end
//.m
#implementation SRCollapsibleCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
}
return self;
}
-(void)formatTitle:(NSString *)title{
if(title.length<30){
self.title.text= title;
self.subtitle.text =#"";
} else {
NSArray *splitString = [self splitString:title maxCharacters:30];
self.title.text = splitString[0];
self.subtitle.text = splitString[1];
splitString = nil;
title = nil;
}
}
////http://www.musicalgeometry.com/?p=1197
- (NSArray *)splitString:(NSString*)str maxCharacters:(NSInteger)maxLength {
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
NSArray *wordArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSInteger numberOfWords = [wordArray count];
NSInteger index = 0;
NSInteger lengthOfNextWord = 0;
while (index < numberOfWords && tempArray.count<2) {
NSMutableString *line = [NSMutableString stringWithCapacity:1];
while ((([line length] + lengthOfNextWord + 1) <= maxLength) && (index < numberOfWords)) {
lengthOfNextWord = [[wordArray objectAtIndex:index] length];
[line appendString:[wordArray objectAtIndex:index]];
index++;
if (index < numberOfWords) {
[line appendString:#" "];
}
}
[tempArray addObject:line];
NSMutableString *subtitle = [NSMutableString stringWithCapacity:1];
while(index<numberOfWords){
[subtitle appendString:[wordArray objectAtIndex:index]];
[subtitle appendString:#" "];
index++;
}
[tempArray addObject:subtitle];
break;
}
return tempArray;
}
//Breaks MVC but it makes the MasterVC cleaner
-(void)updateWithTopic: (SRTopic *)topic
{
[self formatTitle:topic.title];
self.topicId = topic.topicId;
self.agreeDebaters.text = [NSString stringWithFormat:#"%#",topic.agreeDebaters];
self.disagreeDebaters.text = [NSString stringWithFormat:#"%#", topic.disagreeDebaters];
self.observers.text = [NSString stringWithFormat:#"%#", topic.observers];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
#end