My UITableView is not scrolling properly I am using customcell as
My cell for rowAtIndexPath looks like this:
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCellWeather *cell = (CustomCellWeather *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:#"CustomCellWeather" owner:nil options:nil];
for(id currentObject in topLevelObjects) {
if([currentObject isKindOfClass:[UITableViewCell class]])
{
cell = (CustomCellWeather *)currentObject;
// cell = [[[CustomCellWeather alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
break;
}
}
}
int index = indexPath.row;
cell.dayDateLabel.textColor = [UIColor colorWithRed:126/255.0 green:212/255.0 blue:252/255.0 alpha:1];
if(index == 0) {
cell.contentView.backgroundColor = [UIColor colorWithRed:0 green:102/255.0 blue:179/255.0 alpha:0.5];
cell.otherCondition.text = #"";
cell.dayTempMin_HumidityLabel.text = #"";
cell.dayConditionLabel.text = #"";
cell.otherWind.text = #"";
cell.dayWindLabel.text = #"";
cell.dayDateLabel.text = #"Current";
cell.dayTempMaxLabel.text = [[[resCurrTempC stringByAppendingString:#"°C/"] stringByAppendingString:resCurrTempF] stringByAppendingString:#"°F"];
cell.todayCondition.text = resCurrWeatherDesc;
cell.currentWind.text = [[[currWindDir stringByAppendingString:#" at "] stringByAppendingString:currWindSpeed] stringByAppendingString:#"mph"];
cell.currentHumidity.text = [resHumidity stringByAppendingString:#"%"];
NSURL *url = [NSURL URLWithString:currIcon];
cell.dayImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}else {
cell.hiddenLabel.text = #""; //represents todayCondition
cell.todayWind.text = #"";
cell.currentWind.text = #"";
cell.todayHumidity.text = #"";
cell.currentHumidity.text = #"";
if(index == 1) {
cell.contentView.backgroundColor = [UIColor colorWithRed:124/255.0 green:123/255.0 blue:123/255.0 alpha:0.5];
cell.dayDateLabel.text = #"Today";
}else{
//NSDate *today = [NSDate date];
NSString *dateString = [responseDate objectAtIndex:index-1];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE, MMM dd"];
NSCalendar *calender = [NSCalendar currentCalendar];
NSDateComponents *components = [calender components:( NSHourCalendarUnit ) fromDate:dateFromString];
//[components setHour:24*(index-1)];
dateFromString = [calender dateByAddingComponents:components toDate:dateFromString options:0];
NSString *stri = [formatter stringFromDate:dateFromString];
cell.contentView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
cell.dayDateLabel.text = stri;
//[dateFromString release];
[formatter release];
}
cell.dayTempMaxLabel.text = [[[[#"Max: " stringByAppendingString:[responseTempMaxC objectAtIndex:index-1]] stringByAppendingString:#"°C/"] stringByAppendingString:[responseTempMaxF objectAtIndex:index-1]] stringByAppendingString:#"°F"] ;
cell.dayTempMin_HumidityLabel.text = [[[[#"Min: " stringByAppendingString:[responseTempMinC objectAtIndex:index-1]] stringByAppendingString:#"°C/"] stringByAppendingString:[responseTempMinF objectAtIndex:index-1]] stringByAppendingString:#"°F"] ;
cell.dayConditionLabel.text = [responseWeatherDesc objectAtIndex:index-1];
cell.dayWindLabel.text = [[[[responseWindDirection objectAtIndex:index-1]stringByAppendingString:#" at "]stringByAppendingString:[responseWindspeedMiles objectAtIndex:index-1]] stringByAppendingString:#"mph"];
NSURL *url = [NSURL URLWithString:[responseWeatherIconUrl objectAtIndex:index-1]];
cell.dayImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
return cell;}
actually i am parsing weather news from a website
can u tell me how can i solve dis
read following link its may be help u
http://www.e-string.com/content/custom-uitableviewcells-interface-builder
http://blog.webscale.co.in/?p=284
http://www.icodeblog.com/2009/05/24/custom-uitableviewcell-using-interface-builder/
Related
In my custom cell there are three labels: name, date and time.
When I search from namearray it shows proper filtered results, but my date and time label values remain unchanged, it always shows the values of my first and second record's date and time detail.
Code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if(isFiltered)
{
return [arrsearchresult count];
}
return [arrfullname count];
}
// tableView delegate methods
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
AppoinmentTableViewCell *cell = (AppoinmentTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AppoinmentTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.btnCall.tag = indexPath.row;
cell.btnMail.tag = indexPath.row;
cell.btnSms.tag = indexPath.row;
cell.btnCreatePlan.tag = indexPath.row;
cell.btnAppointment.tag = indexPath.row;
cell.btnStatus.tag=indexPath.row;
}
cell.clipsToBounds = YES;
if ([strCheckVC isEqualToString:#"OpenLead"])
{
cell.lblFullname.text = [arrfullname objectAtIndex:indexPath.row];
[self databaseOpen];
NSString *query_user=[ NSString stringWithFormat:#"Select * from lead_status where row_lead_id = %# and lead_followup_datetime != ' ' order by rowid desc limit 1",[arrRowid objectAtIndex:indexPath.row]];
NSArray *rowids = [[NSArray alloc]init];
rowids =[[database executeQuery:query_user]mutableCopy];
NSLog(#"%#",rowids);
[database close];
if (rowids.count > 0 )
{
NSString *dateString = [[rowids valueForKey:#"lead_followup_datetime"]objectAtIndex:0];
NSArray *components = [dateString componentsSeparatedByString:#" "];
NSString *date = components[0];
NSString *time = components[1];
// date convert
NSString *dateStr = [NSString stringWithFormat:#"%#",date];
NSString *timestr = [NSString stringWithFormat:#"%#",time];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date11 = [dateFormat dateFromString:timestr];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date11];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",date];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
NSDate *viewdt = [dateFormat dateFromString:dateStr];
//date11 = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:viewdt];
//
cell.lblDate.text = dateWithNewFormat;
}
else
{
// date convert
NSString *dateStr = [NSString stringWithFormat:#"%#",[appointmenttime objectAtIndex:indexPath.row]];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",[arrappointment_date objectAtIndex:indexPath.row]];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:date];
//
cell.lblDate.text = dateWithNewFormat;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if ([[arremail objectAtIndex:indexPath.row] isEqual:[NSNull null]] || [[arremail objectAtIndex:indexPath.row] isEqualToString:#"<null>"] || [[arremail objectAtIndex:indexPath.row] isEqualToString:#""] )
{
cell.btnMail.hidden = NO;
}
NSUInteger hours_passed = [[arrhours_passed objectAtIndex:indexPath.row] integerValue];
if (hours_passed <= 72)
{
cell.colorView.backgroundColor = [UIColor whiteColor];
}
else if (hours_passed <= 144)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:219.0/255.0 green:157.0/255.0 blue:157.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
else if (hours_passed <= 216)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:202.0/255.0 green:114.0/255.0 blue:114.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
else if (hours_passed <= 288)
{
cell.colorView.backgroundColor = [UIColor colorWithRed:189.0/255.0 green:78.0/255.0 blue:78.0/255.0 alpha:1.0];
cell.lblDate.textColor = [UIColor whiteColor];
cell.lblTime.textColor = [UIColor whiteColor];
cell.lblFullname.textColor = [UIColor whiteColor];
}
[self databaseOpen];
NSString *str = [NSString stringWithFormat:#"Select * from lead_followup where rowid=%#",[arrRowid objectAtIndex:indexPath.row]];
NSMutableArray *arr = [[NSMutableArray alloc]init];
arr = [[database executeQuery:str]mutableCopy];
NSLog(#"arr data %#",arr);
[database close];
NSString *strsms;
if (arr.count != 0)
{
strsms = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_sms"]objectAtIndex:0]];
if ([strsms isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
[cell.btnSms setImage:[UIImage imageNamed:#"Chatgray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
//white
[cell.btnSms setImage:[UIImage imageNamed:#"chatwhite"] forState:UIControlStateNormal];
}
}
/*else
{
// green icon
[cell.btnSms setImage:[UIImage imageNamed:#"Chatgreen"] forState:UIControlStateNormal];
}*/
NSString *strCall = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_call"]objectAtIndex:0]];
NSLog(#"%#",strCall);
if ([strCall isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
//blackCallGray
[cell.btnCall setImage:[UIImage imageNamed:#"CallGray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
[cell.btnCall setImage:[UIImage imageNamed:#"CallWhite"] forState:UIControlStateNormal];
}
}
else
{
[cell.btnCall setImage:[UIImage imageNamed:#"CallGreen"] forState:UIControlStateNormal];
// green icon
}
NSString *strmail = [NSString stringWithFormat:#"%#",[[arr valueForKey:#"followed_by_mail"]objectAtIndex:0]];
NSLog(#"%#",strmail);
if ([strmail isEqualToString:#"0"])
{
if (hours_passed <= 72)
{
[cell.btnMail setImage:[UIImage imageNamed:#"Mailgray"] forState:UIControlStateNormal];
}
else if (hours_passed > 72)
{
[cell.btnMail setImage:[UIImage imageNamed:#"MailWhite"] forState:UIControlStateNormal];
//white
}
}
/*else
{
[cell.btnMail setImage:[UIImage imageNamed:#"MailGreen"] forState:UIControlStateNormal];
// green icon
}*/
}
[cell.btnCall addTarget:self
action:#selector(callDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnSms addTarget:self
action:#selector(smsDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnMail addTarget:self
action:#selector(mailDo:) forControlEvents:UIControlEventTouchDown];
[cell.btnStatus addTarget:self
action:#selector(Status:) forControlEvents:UIControlEventTouchDown];
[cell.btnAppointment addTarget:self
action:#selector(AddappointmentId:) forControlEvents:UIControlEventTouchDown];
[cell.btnCreatePlan addTarget:self
action:#selector(CreatePlan:) forControlEvents:UIControlEventTouchDown];
if(self.btnSearchByName.selected==YES)
{
if(isFiltered)
{
cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
/*cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];*/
}
}
else
{
if(isFiltered)
{
//cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
//cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];
}
}
}
else
{
cell.lblFullname.text = [arrfullname objectAtIndex:indexPath.row];
cell.btnSms.hidden = YES;
cell.btnCall.hidden = YES;
cell.btnMail.hidden = YES;
cell.colorView.hidden =YES;
// cell.lblTime.text = [appointmenttime objectAtIndex:indexPath.row];
//cell.lblDate.text = [arrappointment_date objectAtIndex:indexPath.row];
NSString *dateStr = [NSString stringWithFormat:#"%#",[appointmenttime objectAtIndex:indexPath.row]];
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"hh:mm a"];
NSString *depResult = [df stringFromDate:date];
cell.lblTime.text = depResult;
dateStr = [NSString stringWithFormat:#"%#",[arrappointment_date objectAtIndex:indexPath.row]];
// Convert string to date object
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd"];
date = [dateFormat dateFromString:dateStr];
NSLog(#"%#",date);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date22 = [dateFormatter dateFromString:dateStr];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *dateWithNewFormat = [dateFormatter stringFromDate:date22];
NSLog(#"dateWithNewFormat: %#", dateWithNewFormat);
// df = [[NSDateFormatter alloc]init];
// [df setDateFormat:#"dd MMM yyyy"];
// depResult = [df stringFromDate:date];
//
cell.lblDate.text = dateWithNewFormat;
}
/* UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor clearColor];
[cell setSelectedBackgroundView:bgColorView];*/
if(self.btnSearchByName.selected==YES)
{
if(isFiltered)
{
cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
/*cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];*/
}
}
else
{
if(isFiltered)
{
//cell.lblFullname.text = [arrsearchresult objectAtIndex:indexPath.row];
cell.lblDate.text = [arrsearchresult objectAtIndex:indexPath.row];
//cell.lblTime.text = [arrsearchresult objectAtIndex:indexPath.row];
}
}
return cell;
}
- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if ([strCheckVC isEqualToString:#"OpenLead"])
{
if(self.btnSearchByName.selected==YES)
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrfullname)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
else
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrleadCreatedDate)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
}
else
{
if(self.btnSearchByName.selected==YES)
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
for ( NSString * str in arrfullname)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}
}
}
}
else
{
if(searchText.length==0)
{
isFiltered=NO;
}
else
{
isFiltered=YES;
arrsearchresult=[[NSMutableArray alloc]init];
NSString *searchString = searchBar.text;
for ( NSString * str in arrdatetime)
{
/*NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[arrsearchresult addObject:str];
}*/
NSComparisonResult result = [str compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame) {
[arrsearchresult addObject:str];
}
}
}
}
}
[self.tblAppoinment reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[self.tblAppoinment resignFirstResponder];
}
I am implementing ActionSheetPickerView on my program but when I try to select ActionSheetStyleTextPicker there is nothing comes in PickerView but same code was working for ActionSheetStyleDatePicker and i am able to select date.
I am using IQActionSheetPickerView in my program github.com/hackiftekhar/IQActionSheetPickerView
in my tableView I write this code
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell=(CustomCell *)[ProfileTable dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomeCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (indexPath.section==0) {
if ([[[ProfileTableArray objectAtIndex:indexPath.row] valueForKey:#"DT"]isEqualToString:#"D"]) {
IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:#"Date Picker" delegate:self];
[picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
[picker setTag:1];
//[picker show];
[cell.SInfoTxt setInputView:picker];
} else {
IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:#"Single Picker" delegate:self];
[picker setTitlesForComponenets:customDValues];
[picker setTag:2];
[picker setActionSheetPickerStyle:IQActionSheetPickerStyleTextPicker];
//[picker show];
[cell.SInfoTxt setInputView:picker];
}
}
and I have write this for textPicker or DatePicker
-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray *)titles
{
switch (pickerView.tag)
{
case 1:{
NSString * dateStr =[NSString stringWithFormat:#"%#",[titles objectAtIndex:0]];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSDate *toDateTime = [dateFormat dateFromString:dateStr];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MMM yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:toDateTime];
[(UITextField *)[self.view viewWithTag:tag] setText:stringDate];
[self.view endEditing:YES];
break;
}
case 2: {
//here i want to show my NSArray which was am already stored in array
// so how can i call Textpicker here..??
break;
}
}
In my app, I use Parse. I have it set up like this:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// The className to query on
self.parseClassName = #"Prayers";
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = YES;
// Whether the built-in pagination is enabled
self.paginationEnabled = YES;
// The number of objects to show per page
self.objectsPerPage = 20;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:#"Prayers"];
// 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 (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object
{
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
self.theObject = object;
BOOL anony = [object[#"Anonymous"] boolValue];
if (!anony) {
NSString *names = [[object[#"FirstName"] stringByAppendingString:#" "] stringByAppendingString:object[#"LastName"]];
cell.profileName.text = names;
cell.contentLabel.text = object[#"Request"];
cell.firstName = object[#"FirstName"];
cell.lastName = object[#"LastName"];
cell.iostoken = object[#"DeviceID"];
cell.request = names;
cell.prayerObject = object;
PFFile *thumbnail = object[#"ProfilePic"];
cell.profilePic.image = [UIImage imageNamed:#"AppIcon60x60#2x.png"];
/*[cell.commentButton addTarget:self action:#selector(didTapCommentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.commentButton setTitle:#"Share" forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.commentButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];*/
[thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.profilePic.image = thumbnailImage;
}];
NSString *dates = object[#"dateMade"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM_dd_yyyy"];
NSDate *datefromstring = [formatter dateFromString:dates];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MMM dd, yyyy"];
cell.dateLabel.text = [formatter2 stringFromDate:datefromstring];
UIFont *cellFont = [UIFont fontWithName:#"Verdana-Bold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"Verdana-Bold" size:12];
}
else {
// Configure the cell to show todo item with a priority at the bottom
cell.profileName.text = object[#"Title"];
cell.contentLabel.text = object[#"Request"];
cell.firstName = object[#"FirstName"];
cell.lastName = object[#"LastName"];
cell.iostoken = object[#"DeviceID"];
cell.request = object[#"Title"];
cell.prayerObject = object;
PFFile *thumbnail = object[#"ProfilePic"];
cell.profilePic.image = [UIImage imageNamed:#"AppIcon60x60#2x.png"];
[thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.profilePic.image = thumbnailImage;
}];
NSString *dates = object[#"dateMade"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM_dd_yyyy"];
NSDate *datefromstring = [formatter dateFromString:dates];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"MMM dd, yyyy"];
cell.dateLabel.text = [formatter2 stringFromDate:datefromstring];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
NSString *commentString = entry[#"Request"];
NSString *nameString = #"";
NSLog(#"%#", commentString);
return [Cell heightForCellWithContentString:(NSString *)commentString] +25 ;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
if (_webViewController2 == nil) {
self.webViewController2 = [[[WebViewController2 alloc] initWithNibName:#"WebViewController2" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController2.entry = entry;
[self.navigationController pushViewController:_webViewController2 animated:YES];
[self.objects objectAtIndex:indexPath.row];
}
else {
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
_webViewController.finalObject = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#endif
}
As I understand, that should load up 20 items at a time, and when you scroll to the end of those, load up the next 20. However, once I have 20 items, the app crashes, and I get this message:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 20 beyond bounds [0 .. 19]'
After putting an exception breakpoint in, the line causing the error is in the heightForRow method
PFObject *entry = [self.objects objectAtIndex:indexPath.row];
What's going on?
I have a simple blog app that lists the articles on the main screen as a UITableView. Everything looks fine when first loading, but when I scroll down and back up, it redraws the cells wrong, and...well, just check out this picture.
The code I use for the cells is listed below. What am I doing incorrect?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *substring = #"http://316apps.com/ipreachersblog/wp";
NSRange textRange = [entry.articleImage rangeOfString:substring];
NSString *substring2 = #"http://ipreacher.files.wordpress.com";
NSRange textRange2 = [entry.articleImage rangeOfString:substring2];
if(textRange.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 3;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"Icon-60#2x.png"]];
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.backgroundColor = [UIColor lightGrayColor];
}
else if (textRange2.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 3;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"Icon-60#2x.png"]];
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.backgroundColor = [UIColor lightGrayColor];
}
else {
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
cell.imageView.image = [UIImage imageNamed:#"Icon-60#2x.png"];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.textLabel.numberOfLines = 3;
cell.backgroundColor = [UIColor lightGrayColor];
}
return cell;
}
The cell is custom, its implementation is:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.frame = CGRectMake(1,6,60,60);
float limgW = self.imageView.image.size.width;
if(limgW > 0) {
self.textLabel.frame = CGRectMake(74,self.textLabel.frame.origin.y,self.textLabel.frame.size.width,self.textLabel.frame.size.height);
self.detailTextLabel.frame = CGRectMake(74,self.detailTextLabel.frame.origin.y,self.detailTextLabel.frame.size.width,self.detailTextLabel.frame.size.height);
}
}
#end
I have a number of blog apps. Recently, some of them started experiencing some issues. I use ASIHTTP Classes and GDataXML Classes to parse the xml of a wordpress feed, and put each item (article) into a mutable array. The tableview is then supposed to load all of the stories into a cell for each article. The issue I am having is that new articles are not being displayed on first run, the user is having to Pull to Refresh, and then the new article displays. I ran a test just now on an app. The article was posted a few hours ago. I ran the app, it wasn't there. Pulled to refresh, it showed. Closed down the app completely, restarted it, and it was gone again. Here is the code in the TableView's implementation:
#implementation RootViewController
- (void)refresh {
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"http://bubblycandacebabbles.wordpress.com/?cat=-2008&feed=rss2",
nil];
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[activity startAnimating];
//[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"navbarcopy.png"] forBarMetrics:UIBarMetricsDefault];
self.title = #"Blog";
CGFloat nRed=111.0/255.0;
CGFloat nBlue=209/255.0;
CGFloat nGreen=229.0/255.0;
UIColor *myColor=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
UIBarButtonItem *font = [[UIBarButtonItem alloc] initWithTitle:#"Change Font Size" style:UIBarButtonItemStylePlain target:self action:#selector(fontsizes)];
self.navigationController.navigationItem.rightBarButtonItem = font;
self.tableView.backgroundColor = myColor;
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
[self refresh];
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
// Refresh table here...
[_allEntries removeAllObjects];
[self.tableView reloadData];
[self refresh];
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleImage = [item valueForChild:#"content:encoded"];
NSScanner *theScanner;
NSString *gt =nil;
theScanner = [NSScanner scannerWithString:articleImage];
NSString *comments = [articleUrl stringByAppendingString:#"#respond"];
NSString *commentslink = [NSString stringWithFormat: #"Leave A Comment",comments];
// find start of tag
[theScanner scanUpToString:#"alt=\"\" width=" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:#"/>" intoString:>] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
NSString *test = [articleImage stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:#"%#", gt] withString:#"alt=\"\" width=\"150\" height=\"150\""];
NSString *final = [test stringByReplacingOccurrencesOfString:#"float:none;height:30px" withString:#"float:none;height:1px"];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *dateofarticle = [dateFormatter stringFromDate:articleDate];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *smalltitle = [defaults objectForKey:#"Title"];
NSString *smallbody = [defaults objectForKey:#"Article"];
NSString *bodyoftext = [[[[[[[[[[[#"<head><body bgcolor=\"#6fd1e5\" text=\"#CC0099\"><style type='text/css'>a > img {pointer-events: none;cursor: default;max-width: 310;}</style></head><b><font size=" stringByAppendingString: smalltitle ] stringByAppendingString:#"><div align=\"left\"><FONT FACE=\"noteworthy\">" ]stringByAppendingString:articleTitle] stringByAppendingString:#"</font></b><font size=" ] stringByAppendingString:smallbody ] stringByAppendingString:#"><div align=\"left\"><FONT FACE=\"noteworthy\">"] stringByAppendingString:dateofarticle] stringByAppendingString:#"</div></p><FONT FACE=\"noteworthy\">"] stringByAppendingString:final] stringByAppendingString:commentslink]stringByAppendingString:#"</FONT>"];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:bodyoftext] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *substring = #"http://bubblycandacebabbles.files.wordpress.com";
NSRange textRange = [entry.articleImage rangeOfString:substring];
if(textRange.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
CGFloat nRed=204.0/255.0;
CGFloat nBlue=0/255.0;
CGFloat nGreen=153.0/255.0;
UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"noteworthy" size:16];
UIFont *cellFont2 = [UIFont fontWithName:#"noteworthy" size:12];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 2;
cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - Mother May I Blog", articleDateString];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
cell.textLabel.textColor = myColortext;
cell.detailTextLabel.textColor = myColortext;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"iphoneicon#2x.png"]];
}
else {
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"noteworthy" size:16];
UIFont *cellFont2 = [UIFont fontWithName:#"noteworthy" size:12];
cell.imageView.image = [UIImage imageNamed:#"iphoneicon#2x.png"];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 2;
cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - Mother May I Blog", articleDateString];
CGFloat nRed=204.0/255.0;
CGFloat nBlue=0/255.0;
CGFloat nGreen=153.0/255.0;
UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
cell.textLabel.textColor = myColortext;
cell.detailTextLabel.textColor = myColortext;
}
return cell;
}
You need to invoke
[self.tableView reloadData];
at some point after your data has finished loading. How exactly you do this is a bit tricky, you need some way of telling when your operation queue is empty. Alternatively, you could theoretically call it after each operation in the queue is complete, that way the table will populate one at a time. This could cause problems if the user is on a slow connection, as reloading the table can cause jumps in the user experience, and I'm not positive on the thread safety of calling reloadData from a different thread