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
Related
I have a custom cell for my TableView app. The TableViewController is called "BlogView". My custom cell has a few buttons on it, one being a share button. I want to present a UIActivityViewController when one of the buttons is pressed.
In the header for my custom cell, I have a property:
#property (nonatomic, retain) BlogView *myViewController;
In the custom cell, I have for layoutSubview:
self.commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.commentButton addTarget:self action:#selector(didTapCommentButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.commentButton setTitle:#"Share" forState:UIControlStateNormal];
[self.commentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.commentButton setTitleColor:[UIColor greenColor] forState:UIControlStateHighlighted];
For the selector didTapCommentButtonAction I have:
- (void)didTapCommentButtonAction:(id)sender
{
NSLog(#"CommentButtonTAPPED");
Mail *mail = [[Mail alloc]init];
NSString *html = self.prayerObject[#"Request"];
NSString *thetitle = [self.prayerObject[#"Title"] stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *thedate = self.prayerObject[#"dateMade"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MMM_dd_yyyy"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *theNewDate1 = [dateFormat dateFromString:thedate];
NSString *theNewDate = [dateFormat stringFromDate:theNewDate1];
mail.thehtml = html;
self.nameofhtmlfile = [[[[#"http://www.iprayed4u.net/app/" stringByAppendingString:thetitle] stringByAppendingString:#"_"] stringByAppendingString:theNewDate] stringByAppendingString:#".html"];
// Reminder *thereminder = [[Reminder alloc] init];
//thereminder.thehtml = html;
//thereminder.thetitle = thetitle;
//thereminder.thedate = thedate;
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:#[self] applicationActivities:#[mail]];
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
activityVC.excludedActivityTypes = #[ UIActivityTypePostToWeibo,
UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact,
UIActivityTypeMail,
UIActivityTypePrint
];
}
else {
activityVC.excludedActivityTypes = #[ UIActivityTypePostToWeibo,
UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact,
UIActivityTypeMail,
UIActivityTypePrint,
UIActivityTypeAirDrop
];
}
NSLog(#"Test");
[self.myViewController presentViewController: activityVC animated: YES completion: nil];
}
In BlogView.m
- (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;
// 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];
UIFont *cellFont = [UIFont fontWithName:#"Verdana-Bold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"Verdana-Bold" size:12];
return cell;
}
I get no warnings or errors, but when I click on the button, nothing happens.
Step one: obtain an IBOutlet from the button on your cell to the CustomCell.h file...
#property (weak, nonatomic) IBOutlet UIButton *commentButton;
Step two: In the cellForRowAtIndexPath, add a selector to the button on each cell and dress it up how you wanted it...NOTICE we are adding the selector to each 'cell button' now... not self.commentButton
[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];
Step three: implement the selector method inside of the BlogView.m file rather than inside of the CustomCell.m
I have a PFQueryTableViewController in my app. If it is a root view of a controller, it is fine. However, if I push it onto another view, there is a strange line that goes through the top of each cell.
- (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:self.parseClassName];
// 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;
// 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"];
[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];
return cell;
}
Just having this as root view presents this:
If I present it from another view like this:
-(void)myPrayers {
BlogView1 *prayers = [[BlogView1 alloc] init];
[self.navigationController pushViewController:prayers animated:YES];
}
It looks like this:
That looks like a UITableViewCellSeperatorStyle Property needing to be set to UITableViewCellSeparatorStyleNone...
[_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
OR
set the separator color of your UITableViewCell to clear color
[_table setSeparatorColor:<#(UIColor *)#>]
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
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/
[self.countryList reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:6 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone]; // or NO ;)
My problem is that I have a tableview with 10+ items with only 6 cells in view, but when the data is loaded and the table is scrolled cell 7 has no data in it. How can I reload the data in that 1 cell?
The code above is what I am using and it doesn't work!
---EDIT---
if (cell == nil) {
cell =[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier]autorelease];
//[cell setBackgroundColor: [UIColor clearColor]];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(52.0, 0.0, 200.0, 20.0)] autorelease];
mainLabel.tag = 1;
mainLabel.font = [UIFont systemFontOfSize:14.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.opaque = YES;
mainLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:mainLabel];
revenue = [[[UILabel alloc] initWithFrame:CGRectMake(52.0, 20.0, 150.0, 20.0)] autorelease];
revenue.tag = 3;
revenue.font = [UIFont systemFontOfSize:14.0];
revenue.textAlignment = UITextAlignmentLeft;
revenue.textColor = [UIColor blackColor];
revenue.opaque = YES;
revenue.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:revenue];
promos = [[[UILabel alloc] initWithFrame:CGRectMake(252.0, 20.0, 150.0, 20.0)] autorelease];
promos.tag = 4;
promos.font = [UIFont systemFontOfSize:14.0];
promos.textAlignment = UITextAlignmentLeft;
promos.textColor = [UIColor blackColor];
promos.opaque = YES;
promos.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:promos];
updates = [[[UILabel alloc] initWithFrame:CGRectMake(252.0, 0.0, 200.0, 20.0)] autorelease];
updates.tag = 5;
updates.font = [UIFont systemFontOfSize:14.0];
updates.textAlignment = UITextAlignmentLeft;
updates.textColor = [UIColor blackColor];
updates.opaque = YES;
updates.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:updates];
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)] autorelease];
photo.contentMode= UIViewContentModeScaleToFill;
photo.tag = 2;
photo.opaque = YES;
photo.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:photo];
}
else {
cell.clearsContextBeforeDrawing=YES;
mainLabel = (UILabel *)[cell.contentView viewWithTag:1];
photo = (UIImageView *)[cell.contentView viewWithTag:2];
promos=(UILabel *)[cell.contentView viewWithTag:4];
revenue=(UILabel *)[cell.contentView viewWithTag:3];
updates=(UILabel *)[cell.contentView viewWithTag:5];
if(photo.image){
photo.image=nil;
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageURL =[NSString stringWithString:[(arrayResults*)[tweets objectAtIndex:indexPath.row] myCountryIcon]];
NSArray *myArray = [imageURL componentsSeparatedByString: #"/"];
NSString *fileName = [NSString stringWithString:[myArray lastObject]];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/AppIcons"];
NSString* path = [dataPath stringByAppendingPathComponent:fileName];
UIImage* image = [UIImage imageWithContentsOfFile:path];
if (!image) {
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
// Create an array with the URL and name.
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:fileName,imageURL, nil ];
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
[arr release];
}
else{
photo.image=image;
}
NSString*promostext=[[NSString alloc] initWithFormat:#"promos:%#",[[(arrayResults*)[tweets objectAtIndex:indexPath.row] mypromos]stringValue] ];
NSString*revenuetext=[[NSString alloc] initWithFormat:#"revenue:%#",[(arrayResults*)[tweets objectAtIndex:indexPath.row] myrevenue] ];
NSString*updatestext=[[NSString alloc] initWithFormat:#"updates:%#",[[(arrayResults*)[tweets objectAtIndex:indexPath.row] myupdates]stringValue] ];
mainLabel.text=[(arrayResults*)[tweets objectAtIndex:indexPath.row] myCountryName];
promos.text=promostext;
revenue.text=revenuetext;
updates.text=updatestext;
[promostext release];
[revenuetext release];
[updatestext release];
}
This is typically a misuse in the recycle/reuse mechanism of cellForRowAtIndexPath:.
Cells are reused when you scroll to avoid allocating too much UITableViewCells. So you need to set the content of the cell in cellForRowAtIndexPath: in both case, either if the cell just have been allocated (cell==nil) or if the cell has been reused (cell!=nil).