TableView Disappears on segmented control - ios

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!

Related

Autocomplete text field in iOS not working

i am newbie in iOS development, i want to add autocomplete textfield in my ap i write a code for that like as
- (void)viewDidLoad
{
[self get data];
}
-(void)getdata
{
NSMutableArray *allObjects = [NSMutableArray array];
NSUInteger limit = 1000;
__block NSUInteger skip = 0;
PFQuery *query = [PFQuery queryWithClassName:#"MapInfo"];
[query setLimit: limit];
[query setSkip: skip];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
[allObjects addObjectsFromArray:objects];
if (objects.count == limit) {
skip += limit;
[query setSkip: skip];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
[allObjects addObjectsFromArray:objects];
self.qpinname=[allObjects valueForKey:#"GPIN"];
self.locationarray=[allObjects valueForKey:#"Location"];
self.latitude=[self.locationarray valueForKey:#"lat"];
self.longitude=[self.locationarray valueForKey:#"lng"];
self.address=[allObjects valueForKey:#"Address"];
NSLog(#"Address %#",self.address);
self.usernameArray=[allObjects valueForKey:#"AddedBy"];
}];
}
}
else
{
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
then i got my data array and i want to show it on my table view like as
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
[self.autoaddress removeAllObjects];
for(NSString *curString in self.address)
{
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[self.autoaddress addObject:curString];
}
}
[_autocompleteTableView reloadData];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
_autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section
{
return self.autoaddress.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] ;
}
cell.textLabel.text = [self.autoaddress objectAtIndex:indexPath.row];
return cell;
}
then i got error in code
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
[self.autoaddress removeAllObjects];
for(NSString *curString in self.address)
{
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0) {
[self.autoaddress addObject:curString];
}
}
[_autocompleteTableView reloadData];
}
Here i got error in line NSRange substringRange = [curString rangeOfString:substring]; -[NSNull rangeOfString:]: unrecognized selector sent to instance i find it in google but i not get solution please help me for this
thanks.
Your self.address property is probably NSNull or it contains NSNull if it is an array. You can check if object is NSNull the following way:
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
The code is from this answer.
EDIT: If you use NSMutableArray you can call the method [self.address removeObjectIdenticalTo:[NSNull null]] to remove all NSNull objects from the array after self.address=[allObjects valueForKey:#"Address"];

UIButton in Custom TableViewCell not Changing Value when Selecting

Thanks to #jsetting32 I have a custom UITableViewCell complete with buttons at the bottom of the tableView. However, when I am clicking those buttons, the value for the selectedState is not changing, making it a bit difficult for the end-user to tell if they have clicked it or not.
self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.likeButton addTarget:self action:#selector(didTapLikeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.likeButton setTitle:#"Pray" forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[[self.likeButton titleLabel] setFont:[UIFont fontWithName:#"Verdana" size:12.0f]];
[self.cellView addSubview:self.likeButton];
Try UIControlStateHighlighted instead of UIControlStateSelected
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
So heres how I solve the button issue... There should already be a method within your custom cell that sets the like status... It is set like so
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
if (indexPath.row == [self.objects count])
return [self tableView:tableView cellForNextPageAtIndexPath:indexPath];
PHChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PHChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setDelegate:self];
}
[self setCellAttributesWithCell:cell withObject:[self.object objectAtIndex:indexPath.row] withIndexPath:indexPath];
return cell;
}
- (void)setCellAttributesWithCell:(PHChatCell *)cell withObject:(PFObject *)object withIndexPath:(NSIndexPath *)indexPath
{
if (object) {
[cell setChat:object];
[cell setTag:indexPath.row];
[cell.likeButton setTag:indexPath.row];
if ([[PHCache sharedCache] attributesForMessage:object]) {
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] :
[NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] :
[NSString stringWithFormat:#"%# comments", commentCount];
return;
}
#synchronized(self) {
// Put this in your init method
// self.outstandingSectionHeadersQueries = [NSMutableDictionary dictionary]
if (![self.outstandingSectionHeaderQueries objectForKey:#(indexPath.row)]) {
PFQuery *query = [PHUtility queryForActivitiesOnMessage:object cachePolicy:kPFCachePolicyNetworkOnly];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
#synchronized(self) {
[self.outstandingSectionHeaderQueries removeObjectForKey:#(indexPath.row)];
if (error) return;
NSMutableArray *likers = [NSMutableArray array];
NSMutableArray *commenters = [NSMutableArray array];
BOOL isLikedByCurrentUser = NO;
for (PFObject *activity in objects) {
if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike] && [activity objectForKey:kPHActivityFromUserKey]) {
[likers addObject:[activity objectForKey:kPHActivityFromUserKey]];
} else if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeComment] && [activity objectForKey:kPHActivityFromUserKey]) {
[commenters addObject:[activity objectForKey:kPHActivityFromUserKey]];
}
if ([[[activity objectForKey:kPHActivityFromUserKey] objectId] isEqualToString:[[PFUser currentUser] objectId]] &&
[[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike]) {
isLikedByCurrentUser = YES;
}
}
[[PHCache sharedCache] setAttributesForMessage:object likers:likers commenters:commenters likedByCurrentUser:isLikedByCurrentUser];
if (cell.tag != indexPath.row) return;
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] : [NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] : [NSString stringWithFormat:#"%# comments", commentCount];
}
}];
}
}
}
}
- (void)PHChatCell:(PHChatCell *)cell didTapLikeButton:(UIButton *)button chat:(PFObject *)chat
{
// Disable the button so users cannot send duplicate requests
[cell shouldEnableLikeButton:NO];
//These are private interface properties to handle when the user wants to unlike the prayer
//when the UIActionsheet is loaded
self.chat = chat;
self.likeButton = button;
self.cell = cell;
if (button.selected) {
[[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:#"Unlike" otherButtonTitles:nil] showInView:self.view];
return;
}
BOOL liked = !button.selected;
[cell setLikeStatus:liked];
NSString *originalButtonTitle = button.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
NSNumber *likeCount = [numberFormatter numberFromString:button.titleLabel.text];
[button setTitle:#"Liked" forState:UIControlStateNormal];
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setImage:[UIImage imageNamed:#"ButtonLikeSelected.png"]];
[cell.likeImage setTransform:CGAffineTransformMakeScale(1.5, 1.5)];
} completion:^(BOOL finished){
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setTransform:CGAffineTransformMakeScale(1, 1)];
}];
}];
NSInteger checker = [[cell.likeCount text] integerValue] + 1;
cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
[[PHCache sharedCache] incrementLikerCountForMessage:chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:chat liked:liked];
[PHUtility likeMessageInBackground:chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
BOOL liked = !self.likeButton.selected;
[self.cell setLikeStatus:liked];
[self.likeButton setTitle:#"Like" forState:UIControlStateNormal];
[self.cell.likeImage setImage:[UIImage imageNamed:#"ButtonLike.png"]];
NSInteger checker = [[self.cell.likeCount text] integerValue] - 1;
self.cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
NSString *originalButtonTitle = self.likeButton.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *likeCount = [numberFormatter numberFromString:self.likeButton.titleLabel.text];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
}
[[PHCache sharedCache] decrementLikerCountForMessage:self.chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:self.chat liked:NO];
[PHUtility unlikeMessageInBackground:self.chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.likeButton.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:!succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
}
Here is the query method used in the previous snippet of code (declared in PHUtility class) :
+ (PFQuery *)queryForActivitiesOnMessage:(PFObject *)message cachePolicy:(PFCachePolicy)cachePolicy {
PFQuery *queryLikes = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryLikes whereKey:kPHActivityMessageKey equalTo:message];
[queryLikes whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeLike];
PFQuery *queryComments = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryComments whereKey:kPHActivityMessageKey equalTo:message];
[queryComments whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeComment];
PFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:queryLikes,queryComments,nil]];
[query setCachePolicy:cachePolicy];
[query includeKey:kPHActivityFromUserKey];
[query includeKey:kPHActivityMessageKey];
return query;
}
Here are the PHCache implementation ...
#interface PHCache()
#property (nonatomic, strong) NSCache *cache;
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message;
#end
#implementation PHCache
#synthesize cache;
#pragma mark - Initialization
+ (id)sharedCache {
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
- (id)init {
self = [super init];
if (self) {
self.cache = [[NSCache alloc] init];
}
return self;
}
- (void)clear {
[self.cache removeAllObjects];
}
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message {
[self.cache setObject:attributes forKey:[self keyForMessage:message]];
}
- (NSString *)keyForMessage:(PFObject *)message {
return [NSString stringWithFormat:#"message_%#", [message objectId]];
}
#pragma mark - Global Chat
- (void)setAttributesForMessage:(PFObject *)message
likers:(NSArray *)likers
commenters:(NSArray *)commenters
likedByCurrentUser:(BOOL)likedByCurrentUser {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:likedByCurrentUser],kPHMessageAttributesIsLikedByCurrentUserKey,
#([likers count]),kPHMessageAttributesLikeCountKey,
likers,kPHMessageAttributesLikersKey,
#([commenters count]),kPHMessageAttributesCommentCountKey,
commenters,kPHMessageAttributesCommentersKey,
nil];
[self setAttributes:attributes forMessage:message];
}
- (NSDictionary *)attributesForMessage:(PFObject *)message {
return [self.cache objectForKey:[self keyForMessage:message]];
}
- (NSNumber *)likeCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikeCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSNumber *)commentCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSArray *)likersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikersKey];
}
return [NSArray array];
}
- (NSArray *)commentersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentersKey];
}
return [NSArray array];
}
- (void)setMessageIsLikedByCurrentUser:(PFObject *)message liked:(BOOL)liked {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:[NSNumber numberWithBool:liked] forKey:kPHMessageAttributesIsLikedByCurrentUserKey];
[self setAttributes:attributes forMessage:message];
}
- (BOOL)isMessageLikedByCurrentUser:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [[attributes objectForKey:kPHMessageAttributesIsLikedByCurrentUserKey] boolValue];
}
return NO;
}
- (void)incrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] - 1];
if ([likerCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)incrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] - 1];
if ([commentCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (NSNumber *)messageCountForUser:(PFUser *)user {
NSDictionary *attributes = [self attributesForUser:user];
if (attributes) {
NSNumber *photoCount = [attributes objectForKey:kPHUserAttributesMessageCountKey];
if (photoCount) {
return photoCount;
}
}
return [NSNumber numberWithInt:0];
}
- (void)setMessageCount:(NSNumber *)count user:(PFUser *)user {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForUser:user]];
[attributes setObject:count forKey:kPHUserAttributesMessageCountKey];
[self setAttributes:attributes forUser:user];
}
Like I said in your previous post... It requires a hefty amount of code to make this feature 'optimal'... Reason for the cache object is to limit api requests to the servers. If the cell has been loaded, we're gonna check the cache to see if the attributes for the cell have been loaded, if it hasn't query to the server to get the attributes and set the cache to ensure we don't need to make an api request in the future...
All the variables starting with kPH are constants that you can declare on your own, or how you feel is sufficient... Like I said before, checking out the Anypic project and integrating the features into your app is best. Just copy over the PAPCache class and PAPUtility class over. Just make sure you read over the code to fully understand what is going on to get a better sense of how to integrate the code with yours, and to extend it to add more features to your app.
If you have any issues please feel free to post a comment.
i. While touching use UIControlStateHighlighted as suggested above.
ii. Keep a different color:
Since you have a custom UITableViewCell, you should implement an IBAction and set your UIButton to this using
[self.likeButton addTarget:self action:#selector(select:) forControlEvents:UIControlEventTouchUpInside];
in the .m file of your cell set:
-(IBAction)onSelectCellClicked:(id)sender {
if(self.yourButton.selected) {
self.yourButton.selected = NO;
} else {
self.yourButton.selected = YES;
}
}
Now set the cell's delegate to self in cell for row after putting this in the cell's .h file:
#protocol CustomCellDelegate <NSObject>
#end
#interface CustomCell : UITableViewCell
#property (strong, nonatomic) NSObject<CustomCellDelegate>* delegate;
#end
And put in the VC that is presenting the UITableView using the custom cell.
you can just add this line into 'didTapLikeButtonAction' :
self.likeButton.selected = !self.likeButton.selected;
once you change the selected state, the button will change its title color.
you may also want to add this line for a smoother effect:
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];

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];
}

Did Selected Row App Crash

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];

Resources