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
Related
I am working on chat application. Actually i have 3 arrays. First array stores user name and second array stores chat message and third array stores images. I am picking image from photo gallery.
When user sends any message to the chat wall I display message in bubble.
So I'm writing some conditions like the below:
if arr2 value is not null then displaying chat message
if arr3 value is not null displaying image in chat bubble
if arr2 value is null then i want to hide lbldesc and show only imv gallery image
if arr3 value is null then hide imv gallery image and enable lblDesc
But i got exception like this:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** NSAllocateMemoryPages(4294967295) failed'`
Here is my code:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.selectionStyle=UITableViewCellSelectionStyleNone;
if (itemsDataArr.count>0) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 3, 250, 80)];
imgView.image = [UIImage imageNamed:#"speech-bubble-2-hi.png"];
imgView.layer.borderColor = [UIColor clearColor].CGColor;
imgView.tag = 5;
[cell.contentView addSubview:imgView];
NSArray *arr1=[[NSArray alloc]init];
arr1=[itemsUserNameArr objectAtIndex:indexPath.row];
NSString *strval=[arr1 objectAtIndex:0];
lblTitle=[[UILabel alloc]initWithFrame:CGRectMake(50, 5, 150, 20)];
lblTitle.highlightedTextColor=[UIColor whiteColor];
[cell.contentView addSubview:lblTitle];
[lblTitle setFont:[UIFont boldSystemFontOfSize:14]];
lblTitle.text=strval;
[imgView addSubview:lblTitle];
NSArray *arr2=[[NSArray alloc]init];
arr2=[itemsDataArr objectAtIndex:indexPath.row];
NSArray *arr3=[[NSArray alloc]init];
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr2 isEqual:#""])
{
NSString *strmsg=[arr2 objectAtIndex:0];
lblDesc=[[UILabel alloc]initWithFrame:CGRectMake(50, 22, 300, 20)];
lblDesc.highlightedTextColor=[UIColor whiteColor];
lblDesc.font=[UIFont systemFontOfSize:12.0];
[cell.contentView addSubview:lblDesc];
[lblDesc setHidden:NO];
lblDesc.text=strmsg;
[imgView addSubview:lblDesc];
// imv.hidden=YES;
// [imv setHidden:true];
}
arr3=[itemImgArray objectAtIndex:indexPath.row];
if(![arr3 isEqual:nil])
{
NSString *strImg=[arr3 objectAtIndex:0];
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:strImg]];
//Now data is decoded. You can convert them to UIImage
imv = [[UIImageView alloc]initWithFrame:CGRectMake(93,12, 50, 50)];
imv.image=[UIImage imageWithData:data];
[imgView addSubview:imv];
[lblDesc setHidden:YES];
// lblDesc.hidden=YES;
}
}
return cell;
}
I've used PTSMessagingCell from here:
I've used messages array for texts/images. This is a ruf sample that may help you.
#import "ViewController.h"
#import "PTSMessagingCell.h"
#interface ViewController ()
{
NSMutableArray *messages;
UITextView *sendMsg;
UITableView *chatTable;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
messages = [[NSMutableArray alloc] initWithObjects:#"Hello",[UIImage imageNamed:#"download.jpeg"],#"Check This Out", nil];
chatTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-100)];
chatTable.delegate = self;
chatTable.dataSource = self;
chatTable.separatorColor = [UIColor clearColor];
[self.view addSubview:chatTable];
chatTable.backgroundColor = [UIColor clearColor];
sendMsg = [[UITextView alloc]initWithFrame:CGRectMake(0, chatTable.frame.size.height, self.view.frame.size.width-100, 100)];
sendMsg.textColor = [UIColor blackColor];
sendMsg.delegate = self;
sendMsg.backgroundColor = [UIColor whiteColor];
sendMsg.layer.cornerRadius = 3.0f;
[self.view addSubview:sendMsg];
UIButton *sendMsgbtn = [[UIButton alloc]initWithFrame:CGRectMake(sendMsg.frame.size.width, chatTable.frame.size.height, 100, 100)];
[sendMsgbtn setTitle:#"SEND" forState:UIControlStateNormal];
sendMsgbtn.backgroundColor = [UIColor redColor];
[sendMsgbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[sendMsgbtn addTarget:self action:#selector(sendClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:sendMsgbtn];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[chatTable addGestureRecognizer:tapGestureRecognizer];
}
-(void)sendClicked{
[sendMsg resignFirstResponder];
[chatTable reloadData];
}
#pragma mark - TableView Delegate and DataSource Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*This method sets up the table-view.*/
static NSString* cellIdentifier = #"messagingCell";
PTSMessagingCell * cell = (PTSMessagingCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[PTSMessagingCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
return [(UIImage *)[messages objectAtIndex:indexPath.row] size].height;
}
else{
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
CGSize messageSize = [PTSMessagingCell messageSize:goodMsg];
NSLog(#"%f",messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f);
return messageSize.height + 2*[PTSMessagingCell textMarginVertical] + 40.0f;
}
}
-(void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath {
if (messages.count>0) {
PTSMessagingCell* ccell = (PTSMessagingCell*)cell;
if ([[messages objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]]) {
ccell.sent = YES;
ccell.avatarImageView.image = [UIImage imageNamed:[messages objectAtIndex:indexPath.row]];
ccell.messageLabel.text = #"";
}
else{
ccell.sent = YES;
const char *jsonString = [[NSString stringWithFormat:#"%#",[messages objectAtIndex:indexPath.row]] UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSString *goodMsg = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
ccell.messageLabel.text = [messages objectAtIndex:indexPath.row];
}
ccell.timeLabel.text = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapReceived:)];
[tapGestureRecognizer setDelegate:self];
[ccell addGestureRecognizer:tapGestureRecognizer];
}
}
-(void)tapReceived:(UITapGestureRecognizer *)tapGestureRecognizer
{
// do something, like dismiss your view controller, picker, etc., etc.
[sendMsg resignFirstResponder];
}
Hope this helps.
Create a custom cell and load images in background thread will give better UI performance
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 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 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