Did Selected Row App Crash - ios

Hello everyone I was following a tutorial where I explain how to expand the cells did with selected row
I've implemented all the array and returns the data correctly but when I go to select the cell to expand my application crashes giving me back this error
[ PFObject sizeWithFont : constrainedToSize : lineBreakMode :]: unrecognized selector sent to instance
with the breakpoint I find the point but I do not understand what's wrong ...
The point where the app crashes is
CGSize AltezzaLabel = [ [ ArrayforPost objectAtIndex : index ] sizew sizeWithFont : [ UIFont fontWithName : # " Helvetica " size : 14.0f ] constrainedToSize : MAX lineBreakMode : NSLineBreakByCharWrapping ] ;
Below I provide the implementation for better understanding
#import "FFTimeline.h"
#import "FFCustomCellTimelineSocial.h"
#interface FFTimeline ()
#end
#implementation FFTimeline
#synthesize ArrayforPost, NuovoArray;
#synthesize IsFlashPost;
- (void)viewDidLoad
{
[super viewDidLoad];
self.FFTableView.delegate = self;
self.FFTableView.dataSource = self;
CellaSelezionata = -1;
}
-(void)viewDidAppear:(BOOL)animated {
[self QueryForPost];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ArrayforPost count];
}
-(void)QueryForPost {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:FF_AMICIZIE_CLASS];
[QueryForFriend whereKey:FF_AMICIZIE_A_USER equalTo:[PFUser currentUser]];
[QueryForFriend whereKey:FF_AMICIZIE_STATO equalTo:#"Confermato"];
[QueryForFriend includeKey:FF_AMICIZIE_DA_USER];
PFQuery *QueryYES = [PFQuery queryWithClassName:FF_POST_CLASS];
[QueryYES whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo:[NSNumber numberWithBool:YES]];
[QueryYES whereKey:FF_POST_SCELTI equalTo:[PFUser currentUser]];
PFQuery *normalPostByFriends = [PFQuery queryWithClassName: FF_POST_CLASS];
[normalPostByFriends whereKey: FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByFriends whereKey: FF_POST_UTENTE matchesKey:FF_AMICIZIE_DA_USER inQuery:QueryForFriend];
PFQuery *normalPostByUser = [PFQuery queryWithClassName:FF_POST_CLASS];
[normalPostByUser whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByUser whereKey:FF_POST_UTENTE equalTo: [PFUser currentUser]];
PFQuery *query = [PFQuery orQueryWithSubqueries:#[QueryYES,normalPostByFriends,normalPostByUser]];
[query includeKey:FF_POST_UTENTE];
[query orderByDescending:FF_CREATEDAT];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
NSLog(#"%#", results);
ArrayforPost = [[NSMutableArray alloc] init];
for (PFObject *object in results) {
[ArrayforPost addObject:object];
}
[self.FFTableView reloadData];
}
}];
}
-(CGFloat)valoreAltezzaCella:(NSInteger)index {
CGSize MAX = CGSizeMake(230, 10000);
CGSize AltezzaLabel = [[ArrayforPost objectAtIndex:index] sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:MAX lineBreakMode:NSLineBreakByWordWrapping];
return AltezzaLabel.height;
}
- (FFCustomCellTimelineSocial *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
FFCustomCellTimelineSocial *cell = (FFCustomCellTimelineSocial * )[self.FFTableView dequeueReusableCellWithIdentifier:#"CellPost"];
if (!cell) {
cell = [[FFCustomCellTimelineSocial alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellPost"];
}
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
cell.FFTestoUtenteLabel.frame = CGRectMake(cell.FFTestoUtenteLabel.frame.origin.x, cell.FFTestoUtenteLabel.frame.origin.y, cell.FFTestoUtenteLabel.frame.size.width, AltezzaLabel);
} else {
cell.FFTestoUtenteLabel.frame = CGRectMake(cell.FFTestoUtenteLabel.frame.origin.x, cell.FFTestoUtenteLabel.frame.origin.y, cell.FFTestoUtenteLabel.frame.size.width, 65);
}
PFObject *ObjectPost = [ArrayforPost objectAtIndex:indexPath.row];
cell.FFTestoUtenteLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:#"Testo"];
cell.FFTestoUtenteLabel.text = text;
[cell.FFTestoUtenteLabel setLineBreakMode:NSLineBreakByWordWrapping];
cell.backgroundCell.layer.masksToBounds = YES;
cell.backgroundCell.layer.cornerRadius = 5.0f;
cell.backgroundFotoProfilo.layer.masksToBounds = YES;
cell.backgroundFotoProfilo.layer.cornerRadius = 35.0f;
cell.FFImmagineUtente.layer.masksToBounds = YES;
cell.FFImmagineUtente.layer.cornerRadius = 30.0f;
cell.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
PFObject *rowObject = [ArrayforPost objectAtIndex:indexPath.row];
if([[rowObject objectForKey:FF_POST_FLASH_POST_BOOLEANVALUE ] boolValue]) {
cell.FlashPostImg.image = [UIImage imageNamed:#"FFNotificaFlash"];
}
else {
cell.FlashPostImg.image = [UIImage imageNamed:#" "];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
if (CellaSelezionata == indexPath.row)
{
return [self valoreAltezzaCella:indexPath.row] + 10 * 2;
}
else {
return 65 + 10 * 2;
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self valoreAltezzaCella:indexPath.row] > 65) {
return indexPath;
} else {
return nil;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (CellaSelezionata == indexPath.row) {
CellaSelezionata = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
if (CellaSelezionata >= 0) {
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:CellaSelezionata inSection:0];
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

In your valoreAltezzaCella: method, [ArrayforPost objectAtIndex:index] is a PFObject and not a NSString, so you cannot apply sizeWithFont to it. You probably want something similar to:
PFObject *objectPost = [ArrayforPost objectAtIndex:indexPath.row];
NSString *text = [objectPost objectForKey:#"Testo"];
CGSize altezzaLabel = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14.0f] constrainedToSize:MAX lineBreakMode:NSLineBreakByWordWrapping];

Related

Unable to dequeue a cell when searching table view parse.com iOS

I'm trying to do a search function in my table view, to return objects from my Parse.com class.
I'm getting this error when I try to make a search in the UISearchBar:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier FeaturedTableViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
Here's how I'm doing it:
#interface DiscoverViewController () <UISearchBarDelegate, UISearchDisplayDelegate>
#property (nonatomic, retain) PFQuery *query;
#property (nonatomic, retain) PFObject *category;
#end
#implementation DailyDiscoverViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
self.searchResults = [NSMutableArray array];
_categories = [[NSMutableArray alloc] initWithCapacity:100];
}
- (void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName:#"Projects"];
[query whereKeyExists:#"name"];
[query whereKey:#"name" containsString:searchTerm];
NSArray *results = [query findObjects];
[self.searchResults addObjectsFromArray:results];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
- (void)refresh {
PFQuery *query = [PFQuery queryWithClassName:#"Categories"];
[query orderByDescending:#"name"];
[query findObjectsInBackgroundWithBlock:^(NSArray *posts, NSError *error) {
if (!error) {
//NSLog(#"%#", posts);
} else {
}
[_categories setArray:posts];
[self.tableView reloadData];
[_loadingView stopAnimating];
[_refreshControl endRefreshing];
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
if (section == 0) {
return 1;
} else {
return self.categories.count;
}
} else {
return self.searchResults.count;
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
return 320;
} else {
return 52;
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
_featuredObject = [_featured objectAtIndex:indexPath.row];
DiscoverFeaturedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DiscoverFeaturedTableViewCell" forIndexPath:indexPath];
[(PFFile*)_featuredObject[#"picture"] getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.image1.image = [UIImage imageWithData:data];
}];
return cell;
} else {
_category = [_categories objectAtIndex:indexPath.row];
DiscoverTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"DiscoverTableViewCell" forIndexPath:indexPath];
cell.name.text = _category[#"name"];
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
PFUser *obj2 = [self.searchResults objectAtIndex:indexPath.row];
PFQuery *query = [PFQuery queryWithClassName:#"Projects"];
PFObject *searchedUser = [query getObjectWithId:obj2.objectId];
NSString *first = [searchedUser objectForKey:#"name"];
cell.name.text = [first substringToIndex:1];
cell.name.text = first;
return cell;
}
return cell;
}
}
#end
I think you can look this stack over flow post : POST
K.
Ok,
Try it on viewDidLoad:
YourCustomCell *yourCustomCell = [UINib
nibWithNibName:#"YourCustomCell" bundle:nil]; [self.tableView
registerNib:cellNib forCellReuseIdentifier:#"cell"];
Note: Your custom cell must have a .xib of course.
You could try this, I remember running into this exact issue and this was one of the solutions I tried:
[self.tableView registerClass:[DiscoverTableViewCell class] forCellReuseIdentifier:#"DiscoverTableViewCell"];
However, I distinctly remember that this didn't work. It turned out I hadn't correctly connected the cells in the storyboard. Furthermore, make sure that the class of your storyboard cell has been changed to represent your cell's custom class.

TableView Disappears on segmented control

So I have a uitableviewcontroller with a segmented control in the navigation bar. I can get the tableview to reload the first time at index 0 and the second time at index 1. When I try to go back to the first index and the entire tableview disappears.
The problem only occurs when the segmented control index is 1 and the tableview section 2 is empty. If there are objects in that area, It works fine and I can switch back and forth between the two tableviews.
I also realized that when I pulled down the refresh control, it says that I have an empty array in the debug area. I put breakpoints within the refresh control method to see what the problem with that was and the problem is before the refresh control method gets fired off...how??
This is not a duplicate question and would appreciate any help I can seeing as this the place to go for all answers. Thanks!
Also, the entire uitableviewcontroller class is extremely long so if you would really like to see it please ask
NewsFeed.m File https://dl.dropboxusercontent.com/u/10826637/NewsTableViewController.m
VERY LONG
#import "NewsTableViewController.h"
#import "OtherNewsViewController.h"
#import "MSCellAccessory.h"
#interface NewsTableViewController ()
{
PFUser *_loggedInUser;
NSIndexPath *_newIndexPath;
PFObject *_clubInvite;
PFObject *_clubRequest;
UIRefreshControl *_refreshControl;
PFUser *_clubInviteUser;
PFUser *_clubRequestUser;
int _rowOneCount;
int _rowTwoCount;
NSMutableArray *_myFollowingArray;
}
#end
#implementation NewsTableViewController
- (void)viewDidLoad {
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButtonItem;
[self.segmentControl addTarget:self action:#selector(changedValue) forControlEvents:UIControlEventValueChanged];
_refreshControl = [[UIRefreshControl alloc] init];
[_refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:_refreshControl];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
_loggedInUser = [PFUser currentUser];
_myFollowingArray = [NSMutableArray arrayWithArray:_loggedInUser[#"Following"]];
if (![_myFollowingArray containsObject:_loggedInUser.username]) {
[_myFollowingArray addObject:_loggedInUser.username];
}
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_myFollowingArray];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 1) {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 2) {
[self.tableView reloadData];
}
}
- (void)changedValue {
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_myFollowingArray];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 1) {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[self.tableView reloadData];
}];
} else if (self.segmentControl.selectedSegmentIndex == 2) {
[self.tableView reloadData];
}
}
-(void)refresh:(UIRefreshControl *)refreshControl {
if (self.segmentControl.selectedSegmentIndex == 0) {
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:#"username" containedIn:_loggedInUser[#"Following"]];
PFQuery *newsQuery = [PFQuery queryWithClassName:#"News"];
[newsQuery whereKey:#"Notified" matchesQuery:userQuery];
[newsQuery setLimit:50];
[newsQuery orderByDescending:#"createdAt"];
[newsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.followingNews = objects;
[self.tableView reloadData];
}];
[_refreshControl endRefreshing];
} else {
PFQuery *inviteQuery = [PFQuery queryWithClassName:#"ClubInvites"];
[inviteQuery whereKey:#"Invited" equalTo:_loggedInUser];
[inviteQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[inviteQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowOneCount = number;
[self.tableView reloadData];
}];
PFQuery *requestsQuery = [PFQuery queryWithClassName:#"ClubRequests"];
[requestsQuery whereKey:#"Owner" equalTo:_loggedInUser];
[requestsQuery whereKey:#"Accepted" equalTo:[NSNumber numberWithBool:NO]];
[requestsQuery countObjectsInBackgroundWithBlock:^(int number, NSError *error) {
_rowTwoCount = number;
[self.tableView reloadData];
}];
PFQuery *myNewsQuery = [PFQuery queryWithClassName:#"News"];
[myNewsQuery setLimit:50];
[myNewsQuery orderByDescending:#"createdAt"];
[myNewsQuery whereKey:#"Notified" equalTo:_loggedInUser];
[myNewsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
self.myNews = objects;
[_refreshControl endRefreshing];
[self.tableView reloadData];
}];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
if (self.segmentControl.selectedSegmentIndex == 0) {
return 1;
} else {
return 3;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.segmentControl.selectedSegmentIndex == 0) {
return self.followingNews.count;
} else {
if (section == 2) {
return self.myNews.count;
} else {
return 1;
}
}
}
//Long tableview configuration method for segumented controller
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = #"Cell";
NSString *cellIdentifier2 = #"Cell2";
UITableViewCell *cell = nil;
if (self.segmentControl.selectedSegmentIndex == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
self.cellImageView = (UIImageView *)[cell.contentView viewWithTag:1];
self.cellImageView.layer.cornerRadius = 6.0f;
self.cellImageView.clipsToBounds = YES;
//Create the cell label going into the cell
self.cellLabel = (UILabel *)[cell.contentView viewWithTag:3];
[cell.contentView addSubview:self.cellLabel];
[cell.contentView addSubview:self.cellImageView];
PFObject *eachNews = [self.followingNews objectAtIndex:indexPath.row];
PFUser *notifier = [eachNews objectForKey:#"Notifier"];
PFUser *notified = [eachNews objectForKey:#"Notified"];
[notifier fetchIfNeeded];
[notified fetchIfNeeded];
NSString *notifierString = [[NSString alloc] init];
NSString *notifiedString = [[NSString alloc] init];
NSString *grammer = [[NSString alloc] init];
NSDate *timeStamp = eachNews.createdAt;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, yyyy h:mm a"];
NSString *timeString = [dateFormatter stringFromDate:timeStamp];
if ([notifier.username isEqualToString:_loggedInUser.username]) {
notifierString = #"You";
grammer = #"are";
} else {
notifierString = notifier[#"username"];
grammer = #"is";
}
if ([notified.username isEqualToString: _loggedInUser.username]) {
notifiedString = #"you";
} else {
notifiedString = notified.username;
}
if (notifier[#"profileImage"] == nil) {
UIImage *hermet = [UIImage imageNamed:#"ohyeah.jpg"];
[self.cellImageView setImage:hermet];
} else {
PFFile *imageFile = notifier[#"profileImage"];
[self.cellImageView setImage:[UIImage imageWithData:[imageFile getData]]];
}
NSMutableString *newsText = [[NSMutableString alloc] init];
if ([eachNews[#"Type"] isEqualToString:#"Follow"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# %#. ", notifierString, eachNews[#"Messages"], notifiedString]];
} else if ([eachNews[#"Type"] isEqualToString:#"New Founder"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# %#. ", notifierString, grammer, eachNews[#"Messages"]]];
}
[newsText appendString:timeString];
NSArray *appendedString = [newsText componentsSeparatedByString:#" "];
NSRange dateRange = [newsText rangeOfString:appendedString[1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newsText];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor lightGrayColor]
range:dateRange];
[attrString endEditing];
self.cellLabel.attributedText = attrString;
self.cellLabel.numberOfLines = 0;
self.cellLabel.font = [UIFont systemFontOfSize:14];
CGSize constrainedSize = CGSizeMake(self.cellLabel.frame.size.width , CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.cellLabel.text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > self.cellLabel.frame.size.height) {
requiredHeight = CGRectMake(0,0, self.cellLabel.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.cellLabel.frame;
newFrame.size.height = requiredHeight.size.height + 20;
self.cellLabel.frame = newFrame;
}
if (self.segmentControl.selectedSegmentIndex == 1) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//Invites section
cell.imageView.image = nil;
cell.detailTextLabel.text = nil;
if (indexPath.section == 0) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if (_rowOneCount == 0) {
[cell.textLabel setTextColor:[UIColor lightGrayColor]];
cell.accessoryView = nil;
} else {
[cell.textLabel setTextColor:[UIColor blackColor]];
cell.accessoryView = [MSCellAccessory accessoryWithType:FLAT_DISCLOSURE_INDICATOR color:[UIColor orangeColor]];
}
cell.textLabel.text = [NSString stringWithFormat:#"Invites (%i)", _rowOneCount];
cell.textLabel.font = [UIFont systemFontOfSize:18];
//Requested section
} else if (indexPath.section == 1){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
if (_rowTwoCount == 0) {
[cell.textLabel setTextColor:[UIColor lightGrayColor]];
cell.accessoryView = nil;
} else {
[cell.textLabel setTextColor:[UIColor blackColor]];
cell.accessoryView = [MSCellAccessory accessoryWithType:FLAT_DISCLOSURE_INDICATOR color:[UIColor orangeColor]];
}
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.textLabel.text = [NSString stringWithFormat:#"Requests (%i)", _rowTwoCount];
//Requested count is greater than 0
} else if (indexPath.section == 2) {
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//Create the ImageViwew that is going into the cell
self.cellImageView = (UIImageView *)[cell.contentView viewWithTag:1];
self.cellImageView.layer.cornerRadius = 6.0f;
self.cellImageView.clipsToBounds = YES;
//Create the cell label going into the cell
self.cellLabel = (UILabel *)[cell.contentView viewWithTag:3];
[cell.contentView addSubview:self.cellLabel];
[cell.contentView addSubview:self.cellImageView];
if (self.myNews.count == 0) {
self.cellLabel.text = #"";
} else {
PFObject *myNewsObject = [self.myNews objectAtIndex:indexPath.row];
PFUser *meUser = [myNewsObject objectForKey:#"Notifier"];
[meUser fetchIfNeeded];
NSDate *timeStamp = myNewsObject.createdAt;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, yyyy h:mm a"];
NSString *timeString = [dateFormatter stringFromDate:timeStamp];
if (meUser[#"profileImage"] == nil) {
UIImage *hermet = [UIImage imageNamed:#"ohyeah.jpg"];
[self.cellImageView setImage:hermet];
} else {
PFFile *imageFile = meUser[#"profileImage"];
[self.cellImageView setImage:[UIImage imageWithData:[imageFile getData]]];
}
self.cellImageView.contentMode = UIViewContentModeScaleAspectFit;
NSMutableString *newsText = [[NSMutableString alloc] init];
if ([myNewsObject[#"Type"] isEqualToString:#"Follow"]) {
[newsText appendString:[NSString stringWithFormat:#"%# %# you. ", meUser.username, myNewsObject[#"Messages"]]];
} else if ([myNewsObject[#"Type"] isEqualToString:#"New Founder"]){
[newsText appendString:[NSString stringWithFormat:#"You are %#. ", myNewsObject[#"Messages"]] ];
}
[newsText appendString:timeString];
NSArray *appendedString = [newsText componentsSeparatedByString:#" "];
NSRange dateRange = [newsText rangeOfString:appendedString[1]];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:newsText];
[attrString beginEditing];
[attrString addAttribute: NSForegroundColorAttributeName
value:[UIColor lightGrayColor]
range:dateRange];
[attrString endEditing];
self.cellLabel.attributedText = attrString;
self.cellLabel.numberOfLines = 0;
self.cellLabel.font = [UIFont systemFontOfSize:14];
CGSize constrainedSize = CGSizeMake(self.cellLabel.frame.size.width , CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.cellLabel.text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > self.cellLabel.frame.size.height) {
requiredHeight = CGRectMake(0,0, self.cellLabel.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.cellLabel.frame;
newFrame.size.height = requiredHeight.size.height + 20;
self.cellLabel.frame = newFrame;
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (self.segmentControl.selectedSegmentIndex == 2) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryView = nil;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.imageView.layer.cornerRadius = 6.0f;
cell.imageView.clipsToBounds = YES;
cell.textLabel.text = #"Some Events";
}
return cell;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (self.segmentControl.selectedSegmentIndex == 1) {
NSArray *headerTitles = [[NSArray alloc] initWithObjects:#"Invites", #"Requests", #"Notifications", nil];
NSString *title = [headerTitles objectAtIndex:section];
return title;
} else if (self.segmentControl.selectedSegmentIndex == 0) {
return #"Following News";
} else {
return #"Events";
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.segmentControl.selectedSegmentIndex == 1) {
if (indexPath.section == 0) {
if (_rowOneCount == 0) {
return;
} else {
[self performSegueWithIdentifier:#"showInvites" sender:self.tableView];
}
} else if (indexPath.section == 1) {
if (_rowTwoCount == 0) {
return;
} else {
[self performSegueWithIdentifier:#"showRequests" sender:self.tableView];
}
} else if (indexPath.section == 2) {
return;
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.segmentControl.selectedSegmentIndex == 0) {
if (self.followingNews.count == 0) {
return 50;
} else {
PFObject *eachNews = [self.myNews objectAtIndex:indexPath.row];
PFUser *notifier = [eachNews objectForKey:#"Notifier"];
PFUser *notified = [eachNews objectForKey:#"Notified"];
[notifier fetchIfNeeded];
[notified fetchIfNeeded];
NSString *notifierString = [[NSString alloc] init];
NSString *notifiedString = [[NSString alloc] init];
if ([notifier.username isEqualToString:_loggedInUser.username]) {
notifierString = #"You";
} else {
notifierString = notifier.username;
}
if ([notified.username isEqualToString: _loggedInUser.username]) {
notifiedString = #"you";
} else {
notifiedString = notified.username;
}
NSString *fullString = [[NSString alloc] init];
if ([eachNews[#"Type"] isEqualToString:#"Follow"]) {
fullString = [NSString stringWithFormat:#"%# %# %#.", notifierString, eachNews[#"Messages"], notifiedString];
} else if ([eachNews[#"Type"] isEqualToString:#"New Founder"]) {
fullString = [NSString stringWithFormat:#"%# %#.", notifierString, eachNews[#"Messages"]];
}
CGSize constrainedSize = CGSizeMake(200, CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > 45) {
requiredHeight = CGRectMake(0,0, 200, requiredHeight.size.height);
}
return requiredHeight.size.height + 50;
}
} else {
if (indexPath.section == 2) {
if (self.myNews.count == 0) {
return 50;
} else {
PFObject *myNewsObject = [self.myNews objectAtIndex:indexPath.row];
PFUser *meUser = [myNewsObject objectForKey:#"Notifier"];
[meUser fetchIfNeeded];
NSString *fullString = [[NSString alloc] init];
if ([myNewsObject[#"Type"] isEqualToString:#"Follow"]) {
fullString = [NSString stringWithFormat:#"%# %# you.", meUser.username, myNewsObject[#"Messages"]];
} else if ([myNewsObject[#"Type"] isEqualToString:#"New Founder"]) {
fullString = [NSString stringWithFormat:#"You are %#.", myNewsObject[#"Messages"]];
}
CGSize constrainedSize = CGSizeMake(200, CGFLOAT_MAX);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:14.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.height > 45) {
requiredHeight = CGRectMake(0,0, 200, requiredHeight.size.height);
}
return requiredHeight.size.height + 50;
}
} else {
return 50;
}
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
OtherNewsViewController *otherVC = segue.destinationViewController;
if ([segue.identifier isEqualToString:#"showInvites"]) {
otherVC.segueIdentifier = #"Invites";
otherVC.navigationItem.title = #"Invites";
} else if ([segue.identifier isEqualToString:#"showRequests"]) {
otherVC.segueIdentifier = #"Requests";
otherVC.navigationItem.title = #"Requests";
}
}
#end
Nevermind I found the answer/where the problem was! in heightForRowAtIndexPath method, I was passing in the wrong array when grabbing the objects
if (self.followingNews.count == 0) {
return 50;
} else {
PFObject *eachNews = [self.myNews objectAtIndex:indexPath.row];
This the array in the first part of the IF statement was not used in the initialization of PFObject. I was using self.myNews instead. I guess figuring out problems really just takes time!

UITableView setSeparatorInset does not work properly

I am trying to have a custom inset for the separator in a UITableView. Here is my code for viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[ChatTableCell class] forCellReuseIdentifier:#"ChatCell"];
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
}
The cell separator inset does not work properly as shown in the picture. It works for some cells and does not for others. What am I doing wrong here?
This is what my viewcontroller.m file looks like
#import "ChatListViewController.h"
#interface ChatListViewController ()
#end
#implementation ChatListViewController
- (id)initWithStyle:(UITableViewStyle)style {
//self = [super initWithStyle:style];
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
self.parseClassName = kChatRoomClassKey;
self.paginationEnabled = YES;
self.pullToRefreshEnabled = YES;
self.objectsPerPage = 25;
//[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
}
return self;
}
- (PFQuery *)queryForTable {
if (![PFUser currentUser]) {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query setLimit:0];
return query;
}
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
[query whereKey:kChatRoomUsersKey equalTo:[PFUser currentUser]];
[query includeKey:kChatRoomUsersKey];
[query orderByDescending:#"updatedAt"];
[query setCachePolicy:kPFCachePolicyCacheThenNetwork];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
//
// If there is no network connection, we will hit the cache first.
if (self.objects.count == 0 || ![[UIApplication sharedApplication].delegate performSelector:#selector(isParseReachable)]) {
[query setCachePolicy:kPFCachePolicyCacheThenNetwork];
}
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = #"ChatCell";
ChatTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ChatTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSArray *users = [object objectForKey:kChatRoomUsersKey];
PFUser *cellUser = (PFUser *)[users objectAtIndex:0];
if ([cellUser.objectId isEqualToString:[PFUser currentUser].objectId]) {
cellUser = [users objectAtIndex:1];
NSLog(#"%#", cellUser);
}
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontLightKey size:14];
if ([cellUser isEqual:[NSNull null]]) {
cell.username.text = #"Selfie User";
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.latestText.text = [object objectForKey:kChatRoomLatestTextKey];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontKey size:10.0];
[cell.avatarImageView.profileImageView setImage:[UIImage imageNamed:#"AvatarPlaceholder.png"]];
}
else {
cell.username.text = cellUser.username;
cell.textLabel.font = [UIFont fontWithName:kDefaultFontKey size:17.0];
cell.latestText.text = [object objectForKey:kChatRoomLatestTextKey];
cell.detailTextLabel.font = [UIFont fontWithName:kDefaultFontKey size:10.0];
if ([[cellUser fetchIfNeeded] objectForKey:kPAPUserProfilePicSmallKey] == nil) {
[cell.avatarImageView.profileImageView setImage:[UIImage imageNamed:#"AvatarPlaceholder.png"]];
}
else
[cell.avatarImageView setFile:[cellUser objectForKey:kPAPUserProfilePicSmallKey]];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 70.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *chatRoomObject = [self.objects objectAtIndex:indexPath.row];
if ([[chatRoomObject objectForKey:kChatRoomReadKey] isEqual:#NO]) {
[chatRoomObject setObject:#YES forKey:kChatRoomReadKey];
[chatRoomObject saveEventually];
UITabBarItem *tabBarItem = [[self.tabBarController.viewControllers objectAtIndex:PAPFriendsTabBarItemIndex] tabBarItem];
NSString *currentBadgeValue = tabBarItem.badgeValue;
if (currentBadgeValue && currentBadgeValue.length > 1) {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *badgeValue = [numberFormatter numberFromString:currentBadgeValue];
NSNumber *newBadgeValue = [NSNumber numberWithInt:[badgeValue intValue] - 1];
tabBarItem.badgeValue = [numberFormatter stringFromNumber:newBadgeValue];
} else {
tabBarItem.badgeValue = #"";
}
}
ChatViewController *convoVC = [[ChatViewController alloc] init];
NSArray *users = [[self.objects objectAtIndex:indexPath.row] objectForKey:kChatRoomUsersKey];
PFUser *cellUser = (PFUser *)[users objectAtIndex:0];
if ([cellUser.objectId isEqualToString:[PFUser currentUser].objectId]) {
cellUser = [users objectAtIndex:1];
}
[convoVC setUser:cellUser];
[convoVC setChatRoom:[self.objects objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:convoVC animated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerClass:[ChatTableCell class] forCellReuseIdentifier:#"ChatCell"];
[self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 65, 0, 0)];
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
[self.navigationItem setTitle:#"Chat"];
//Change Back button text
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle: #""
style: UIBarButtonItemStyleBordered
target: nil action: nil];
[self.navigationItem setBackBarButtonItem: backButton];
[self.navigationController setDelegate:self];
}
-(void)viewDidAppear:(BOOL)animated {
[self loadObjects];
//Google Analytics screen tracking
id tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:kGAIScreenName
value:#"Chat"];
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}
-(void)viewWillAppear:(BOOL)animated {
[Flurry logEvent:#"Viewed Chat" timed:YES];
}
-(void)viewWillDisappear:(BOOL)animated {
[Flurry endTimedEvent:#"Viewed Chat" withParameters:nil];
}
#end
After all my workaround , now fixed in both ios 7 and 8 tested.
-(void)viewDidLayoutSubviews
{
[customTableview setSeparatorInset:UIEdgeInsetsZero];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(customCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:#selector(setSeparatorInset:)]){
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:#selector(setLayoutMargins:)]) {
[tableView setLayoutMargins:UIEdgeInsetsZero]; // ios 8 newly added
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}

My TableView crashes when I make the run App

I state that in my app I'm using Parse.com for storing and managing data.
In my tableview I have introduced two different custom cells. A is displayed if there is an image and the other hand is displayed if the image is not present.
Now everything seems to work but when I go to make the application run the Tableview crash reporting this error:
2013-11-22 15:36:34.256 UniGo![17186:70b]
Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:],/SourceCache/UIKit_Sim/UIKit-2903.23/UITableView.m:6246**
Can you explain where I'm wrong?
- (void)viewDidLoad {
[super viewDidLoad];
self.FFTableView.delegate = self;
self.FFTableView.dataSource = self;
CellaSelezionata = -1;
}
-(void)viewDidAppear:(BOOL)animated {
[self QueryForPost];
}
-(void)QueryForPost {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:FF_AMICIZIE_CLASS];
[QueryForFriend whereKey:FF_AMICIZIE_A_USER equalTo:[PFUser currentUser]];
[QueryForFriend whereKey:FF_AMICIZIE_STATO equalTo:#"Confermato"];
[QueryForFriend includeKey:FF_AMICIZIE_DA_USER];
PFQuery *QueryYES = [PFQuery queryWithClassName:FF_POST_CLASS];
[QueryYES whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo:[NSNumber numberWithBool:YES]];
[QueryYES whereKey:FF_POST_SCELTI equalTo:[PFUser currentUser]];
PFQuery *normalPostByFriends = [PFQuery queryWithClassName: FF_POST_CLASS];
[normalPostByFriends whereKey: FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByFriends whereKey: FF_POST_UTENTE matchesKey:FF_AMICIZIE_DA_USER inQuery:QueryForFriend];
PFQuery *normalPostByUser = [PFQuery queryWithClassName:FF_POST_CLASS];
[normalPostByUser whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByUser whereKey:FF_POST_UTENTE equalTo: [PFUser currentUser]];
PFQuery *query = [PFQuery orQueryWithSubqueries:#[QueryYES,normalPostByFriends,normalPostByUser]];
[query includeKey:FF_POST_UTENTE];
[query orderByDescending:FF_CREATEDAT];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
ArrayforPost = [[NSMutableArray alloc] init];
for (PFObject *object in results) {
[ArrayforPost addObject:object];
}
[self.FFTableView reloadData];
}
}];
}
-(CGFloat)valoreAltezzaCella:(NSInteger)index {
PFObject *objectPost = [ArrayforPost objectAtIndex:index];
NSString *text = [objectPost objectForKey:#"Testo"];
CGSize MAX = CGSizeMake(230, 10000);
UIFont *FONT = [UIFont systemFontOfSize:14];
CGSize altezzaLabel = [text boundingRectWithSize:MAX options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
return altezzaLabel.height;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ArrayforPost count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *ObjectPost = [ArrayforPost objectAtIndex:indexPath.row];
// FIRST CUSTOM CELL
if (![ObjectPost objectForKey:FF_POST_IMMAGINE]) {
static NSString *IdentificazioneCella = #"CellPost";
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCella ];
}
Cella.backgroundCell.layer.cornerRadius = 2.0f;
Cella.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.backgroundCell.layer.borderWidth = 1.0f;
Cella.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.BackgroundText.layer.cornerRadius = 2.0f;
Cella.BackgroundText.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.BackgroundText.layer.borderWidth = 0.0f;
Cella.BackgroundText.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.TimeBackground.layer.cornerRadius = 2.0f;
Cella.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.TimeBackground.layer.borderWidth = 1.0f;
Cella.ViewTestataCell.layer.cornerRadius = 2.0f;
Cella.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.ViewTestataCell.layer.borderWidth = 1.0f;
Cella.FFImmagineUtente.layer.masksToBounds = YES;
Cella.FFImmagineUtente.layer.cornerRadius = 20.0f;
Cella.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
Cella.FFTestoUtenteLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
Cella.FFTestoUtenteLabel.text = text;
[Cella.FFTestoUtenteLabel setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
Cella.DataCorrente.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
Cella.FFNomeUtenteLabel.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
Cella.FFImmagineUtente.file = (PFFile *)ImmagineUtente;
[Cella.FFImmagineUtente loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, AltezzaLabel); }
else {
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, 55);
}
PFObject *rowObject = [ArrayforPost objectAtIndex:indexPath.row];
if([[rowObject objectForKey:FF_POST_FLASH_POST_BOOLEANVALUE ] boolValue]) {
Cella.FlashPostImg.image = [UIImage imageNamed:#"FFNotificaFlash"];
}
else {
Cella.FlashPostImg.image = [UIImage imageNamed:#" "]; }
return Cella;
}
else {
// SECOND CUSTOM CELL
static NSString *IdentificazioneCellaIMG = #"CellIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCellaIMG ];
}
NSString *FotoPostSocial = [ObjectPost objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.TimeBackground.layer.cornerRadius = 2.0f;
CellaIMG.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.TimeBackground.layer.borderWidth = 1.0f;
CellaIMG.ViewTestataCell.layer.cornerRadius = 2.0f;
CellaIMG.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.ViewTestataCell.layer.borderWidth = 1.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 20.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
CellaIMG.DataPost.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel);
}
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 75);
}
return CellaIMG;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
if (CellaSelezionata == indexPath.row) {
//SPAZIO INTERNO VERSO IL BASSO QUANDO APRI LA CELLA
return [self valoreAltezzaCella:indexPath.row] + 60 * 2;
}
else {
//GRANDEZZA CELLA PRIMA DI APRIRE
return 155 + 10 * 2;
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self valoreAltezzaCella:indexPath.row] > 65) {
return indexPath;
} else {
return nil;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (CellaSelezionata == indexPath.row) {
CellaSelezionata = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
if (CellaSelezionata >= 0) {
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:CellaSelezionata inSection:0];
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
dequeueReusableCellWithIdentifier - can return you nil
You need to check that and create a cell if that happens:
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}

Prepare for segue SearchDisplayController with Parse.com

in my app I'm using Parse.com as the holder of the data on a database and SearchBarDisplayController for research. I have prepared a following to prepare for my table in order to send the data cells in another view controller and works perfectly ... Now I am having a problem ...
How can I create a "prepareforsegue" for the SearchDisplayController, to activate the cells of the search results?
In here you can see the code for "Prepare for Segue" (or another Method) that I made and the data to be passed ...
Some Ideas on this? Thanks so much!
#import "Ricerca.h"
#import "Custom.h"
#import "DettagliProfilo.h"
#interface Ricerca () <UISearchDisplayDelegate, UISearchBarDelegate>
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
#implementation Ricerca
#synthesize searchResults;
- (void)viewDidLoad {
[super viewDidLoad];
[self loadObjects];
self.searchResults = [NSMutableArray array];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"_User";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 10;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
//[query whereKeyExists:#"username"];
//[query whereKeyExists:#"email"];
[query orderByAscending:#"username"];
if ([self.objects count] == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
return query;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
UITableViewCell *cell = (UITableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
// Configure the cell
UIColor *color = [[UIColor alloc] initWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
cell.detailTextLabel.backgroundColor = color;
cell.textLabel.backgroundColor = color;
if (tableView == self.tableView) {
cell.textLabel.text = [object objectForKey:#"username"];
cell.detailTextLabel.text = [object objectForKey:#"email"];
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [object objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
}
else if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"username"];
NSString *email = [searchedUser objectForKey:#"email"];
cell.detailTextLabel.text = email;
cell.textLabel.text = content;
cell.imageView.image = [UIImage imageNamed:#"unknown"];
PFFile *imageFile = [searchedUser objectForKey:#"foto"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
cell.imageView.image =[UIImage imageWithData:data];
}];
NSLog(#"Content: %#", content);
}
return cell;
}
- (void)callbackLoadObjectsFromParse:(NSArray *)result error:(NSError *)error {
if (!error) {
[self.searchResults removeAllObjects];
NSLog(#"Successfully fetched %d entries", result.count);
[self.searchResults addObjectsFromArray:result];
[self.searchDisplayController.searchResultsTableView reloadData];
} else {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFUser query];
[query orderByAscending:#"username"];
[query whereKeyExists:#"email"];
[query whereKey:#"username" containsString:searchTerm];
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query findObjectsInBackgroundWithTarget:self selector:#selector(callbackLoadObjectsFromParse:error:)];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 80.0f; // or some other height
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
} else {
[super tableView:tableView didSelectRowAtIndexPath:indexPath];
}
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Check that a new transition has been requested to the DetailViewController and prepares for it
/*if ([segue.identifier isEqualToString:#"Dettaglio"]){
// Capture the object (e.g. exam) the user has selected from the list
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;*/
if ([[segue identifier]isEqualToString:#"Dettaglio"])
{
DettagliProfilo *sdvc = (DettagliProfilo *)[segue destinationViewController];
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
sdvc.Dettaglio = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DettagliProfilo *detailViewController = [segue destinationViewController];
detailViewController.Dettaglio = object;
}
}
}
#end

Resources