UITableViewCell Duplicate Behavior With UIButton SetTitle And Cell Reuse? - ios

I'm getting some really unusual behavior with my application. I have a tableview that loads cells based on data from a server, The data coming from the server is great, no duplicates and is how it should be. However as I scroll through my table I'm noticing UIButtons that I use setTitle on are showing duplicate title that were previously shown while scrolling, as if the reused cells aren't updating the title in some cases when setTitle is called..
UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
NSDictionary *tag = [self.tags objectAtIndex:indexPath.row];
ArgumentButton *nameButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_NAME];
[nameButton addTarget:self action:#selector(tagSelected:) forControlEvents:UIControlEventTouchUpInside];
[nameButton setTitle:[NSString stringWithFormat:#"#%#", [tag objectForKey:#"tag"]] forState:UIControlStateNormal];
nameButton.argument = [tag objectForKey:#"tag"];
UILabel *totalFollowersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_FOLLOWERS];
totalFollowersLabel.text = [tag objectForKey:#"followers"];
UILabel *followersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOWERS];
UIView *dividerView = (UIView *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_DIVIDER];
UILabel *totalProductsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_PRODUCTS];
totalProductsLabel.text = [tag objectForKey:#"products"];
UILabel *productsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_PRODUCTS];
if (self.allowFollow) {
totalFollowersLabel.frame = CGRectMake(30, totalFollowersLabel.frame.origin.y, totalFollowersLabel.frame.size.width, totalFollowersLabel.frame.size.height);
followersLabel.frame = CGRectMake(30, followersLabel.frame.origin.y, followersLabel.frame.size.width, followersLabel.frame.size.height);
dividerView.frame = CGRectMake(133, dividerView.frame.origin.y, dividerView.frame.size.width, dividerView.frame.size.height);
totalProductsLabel.frame = CGRectMake(157, totalProductsLabel.frame.origin.y, totalProductsLabel.frame.size.width, totalProductsLabel.frame.size.height);
productsLabel.frame = CGRectMake(157, productsLabel.frame.origin.y, productsLabel.frame.size.width, productsLabel.frame.size.height);
NSString *followButtonTitle = ([[tag objectForKey:#"followed"] isEqualToString:#"1"]) ? #"Unfollow" : #"Follow";
ArgumentButton *followButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOW];
followButton.argument = indexPath;
[followButton addTarget:self action:#selector(followSelected:) forControlEvents:UIControlEventTouchUpInside];
[followButton setTitle:followButtonTitle forState:UIControlStateNormal];
followButton.hidden = NO;
}
HorizontalScroll *scroll = (HorizontalScroll *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_SCROLL];
scroll.contentOffset = CGPointMake(-5, 0);
scroll.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
scroll.pagingEnabled = NO;
[scroll resetItems];
NSArray *items = [tag objectForKey:#"items"];
NSMutableArray *scrollItems = [[NSMutableArray alloc] init];
for (NSDictionary *item in items) {
NSArray *scrollItemXIB = [[NSBundle mainBundle] loadNibNamed:#"DetailedFeedScrollItemView" owner:self options:nil];
UIView *scrollItemView = [scrollItemXIB lastObject];
ArgumentButton *itemButton = (ArgumentButton *)[scrollItemView viewWithTag:DETAILED_FEED_SCROLL_ITEM_TAG_BUTTON];
[itemButton sd_setImageWithURL:[APIController resourceUrlForUserId:[item objectForKey:#"userId"] resourceName:[item objectForKey:#"thumbnail"]] forState:UIControlStateNormal];
[itemButton addTarget:self action:#selector(productSelected:) forControlEvents:UIControlEventTouchUpInside];
itemButton.argument = [item objectForKey:#"id"];
[scrollItems addObject:scrollItemView];
}
[scroll loadItems:scrollItems];
return cell;
Note: I am using UITableViewCells within their own XIB for this, which is set like this in viewDidLoad.
[self registerNib:[UINib nibWithNibName:#"DetailedTagsFeedTableViewCell" bundle:nil] forCellReuseIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
It's as if [nameButton setTitle:] is not setting the right titles while scrolling? I've tried a little debugging by setting the followersLabel text equal to the same value that we're attempting to set with setTitle on the nameButton, and the value IS correct when setting the .text property of the label in the same cell.. Very confusing.
The Argument button class is nothing special. Just a simple subclass that has a public property for passing an argument with itself to a target/action.

Related

Change UIButton Color in UITableViewCell onload

I have a list of contacts, app can add/view details. I added a star button in my custom UITableViewCell, It is for "Favorites" functionality. I want my button to be color yellow if the contact is 'Favorited' and Gray if not. Here is my code.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
forIndexPath:indexPath];
ContactUtilities *cu = [[ContactUtilities alloc]init];
NSMutableDictionary *listToUse = [NSMutableDictionary new];
if([self.txtSearchContacts.text isEqualToString:#""]){
listToUse = self.contactList;
} else {
listToUse = searchContactList;
}
NSArray *keyList = [listToUse allKeys];
NSString *search = [keyList objectAtIndex:indexPath.row];
Contact *contact = [[Contact alloc]init];
contact = [cu searchContact:search :listToUse];
//Tagging
UILabel *lblContactName = [cell.contentView viewWithTag:ContactCellElementName];
UIImageView *imgContactPic = [cell.contentView viewWithTag:ContactCellElementImage];
UILabel *lblContactCompany = [cell.contentView viewWithTag:ContactCellElementCompany];
UILabel *lblContactNumber = [cell.contentView viewWithTag:ContactCellElementNumber];
UIButton *isFavorite = (UIButton *)[cell viewWithTag:ContactCellElementButton];
UIImage* image = [UIImage imageNamed:contact.imageName];
CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];
if (cim == nil && cgref == NULL)
{
image = [UIImage imageNamed:#"Person"];
}
lblContactName.text = contact.contactName;
imgContactPic.image = image;
lblContactCompany.text = contact.contactCompanyName;
lblContactNumber.text = contact.contactPhoneNumber;
//This is where it doesn't work..
if([contact.isFavorite isEqualToString:#"YES"]){
[isFavorite setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
} else {
[isFavorite setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}
//I also have a property that will check if you will show the button. This is working already.
if([contact.shouldShow isEqualToString:#"No"]){
[isFavorite removeFromSuperview];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
That is my cellForRowAtIndexPath code. I am currently trying the setTitleColor property but it doesn't work. Same as the setTintColor it doesn't work either.
Tint color is what you want, but it only works if the image is a PNG with an alpha channel, and the rendering mode of the image is set to template. Refer to this answer. If you're assigning the image to the button in a storyboard, you can set the rendering mode in the asset library.

selector for multiple uibuttons in uitableviewcell

I'm adding the same selector for multiple UIButtons which are part of a UITableViewCell and it works only for the first one. Am I missing something?
Here's my code:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *d = [tableData objectAtIndex:indexPath.row];
NSArray *answers = [d objectForKey:#"answers"];//array of { id = 35; text = "\U03c4\U03a\U03c0\U03bf\U03c4\U03b1"; }
UILabel *startDate = (UILabel *)[cell viewWithTag:100];
long long startDateEpoch = [[d objectForKey:#"startDate"] longLongValue];
NSDate *sDate = [NSDate dateWithTimeIntervalSince1970:startDateEpoch/1000];
NSDateFormatter *startDateFormatter = [[NSDateFormatter alloc] init];
[startDateFormatter setDateFormat:#"dd/MM/yyyy"];
startDate.text = [startDateFormatter stringFromDate:sDate];
((UILabel *)[cell viewWithTag:101]).text = [d objectForKey:#"subject"];
NSArray *tags = [d objectForKey:#"tags"];
((UILabel *)[cell viewWithTag:102]).text = [tags componentsJoinedByString:#" "];
NSString *imageURL = [d objectForKey:#"media"];
UIImageView *iv = (UIImageView *)[cell viewWithTag:103];
iv.contentMode = UIViewContentModeScaleAspectFit;
[iv sd_setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
UIView *buttonsContainer = (UIView *)[cell viewWithTag:104];
for(UIView *vv in buttonsContainer.subviews){
[vv removeFromSuperview];
}
int index = 0;
NSLog(#"buttonsContainer children: %d", buttonsContainer.subviews.count);
for(NSDictionary *answer in answers){
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, index * 40 + (index+1)*5, [UIScreen mainScreen].bounds.size.width, 40)];
v.backgroundColor = [UIColor whiteColor];
CGRect labelFrame = v.frame;
labelFrame.origin.y = 0;
UILabel *l = [[UILabel alloc] initWithFrame:labelFrame];
l.text = (NSString *)[answer objectForKey:#"text"];
l.textAlignment = NSTextAlignmentCenter;
UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, v.frame.size.height - 1, v.frame.size.width, 1)];
bottomLine.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:205.0/255.0 blue:103.0/255.0 alpha:1.0];
UIButton *b = [[UIButton alloc] initWithFrame:v.frame];
[b addTarget:self action:#selector(answered:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:l];
[v addSubview:bottomLine];
[v addSubview:b];
[buttonsContainer addSubview:v];
index++;
}
}
So for example if 4 buttons are added, the selector is called only when I click on the first one. When I click on the other three nothing happens.
EDIT:
adding the answered: code:
- (void)answered:(UIButton *)sender
{
NSLog(#"#answered");
}
ok, I found it. Many cudos to TomSwift since his point gave me the idea to place borders on all the views in order to debug their frames size and origin.
Notice that I give to my buttons the same frame as their superviews, which is wrong since they should not have the same origin. The buttons' origin should be 0,0 since they have the same frame size as their superviews.
lessons learn for noobs like me:
When a button does not work, place borders in order to make sure their frame is within the superview's bounds.
Do not assign the same frame on a view and its subview. It will place it outside of the superview's bounds which in 92% of the cases brings undesirable behaviour.

UITableViewCell not showing first MPMoviePlayerController video on the cell in iOS 7?

I am trying to add video on UITableViewCell the video is adding perfectly but the problem is that when I add second video the first cell on UITableViewCell is got black and second cell showing video.
I want all my cell showing video first frame(video picture)
But it is showing only last one(Last cell)
Then I add UIButton to play every cell video it is working perfectly.
My Problem is that I want all my cell showing video first frame(video picture) on every UITableViewCell.
But problem is if only one cell add then it is showing video first picture perfectly. Then I click button and its started video perfectly but when I add second video the first one got black and second one work perfectly.
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section==0) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"listData"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil] autorelease];
cell.selectedBackgroundView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#".png"] ];
cell.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#".png"] ];
[cell setBackgroundColor:[UIColor clearColor]];
UILabel * lbl =[[UILabel alloc]initWithFrame:CGRectMake(330, 80, 135, 41)];
lbl.backgroundColor = [UIColor clearColor];
lbl.text = #"Play Video Here";
[cell.contentView addSubview:lbl];
NSInteger x = [[NSUserDefaults standardUserDefaults] integerForKey:#"cellRowNumber"];
NSLog(#"x is %d",x);
if (x<1) {
x = 0;
}
NSURL* url = [UIAppDelegate.videoUrlsArray objectAtIndex:indexPath.row];
NSLog(#"selected tableview row is %d",indexPath.row);
NSInteger p = indexPath.row ;
NSLog(#"P is %d",p);
secView2 =[[UIView alloc]initWithFrame:CGRectMake(84,5,600,170)];
secView2.tag = indexPath.row;
secView2.backgroundColor = [UIColor redColor];
[cell.contentView addSubview:secView2];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
moviePlayer.view.frame = CGRectMake(0,0,600,170);
moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
[moviePlayer prepareToPlay];
moviePlayer.shouldAutoplay = NO;
[secView2 addSubview:moviePlayer.view];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = indexPath.row;
playBtn.frame = CGRectMake(0,0,600,170);
[playBtn setBackgroundColor:[UIColor clearColor]];
playBtn.tag = indexPath.row;
[playBtn addTarget:self action:#selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
[secView2 addSubview:playBtn];
}
// moviePlayer.contentURL = [UIAppDelegate.videoUrlsArray objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//[self.moviePlayer pause];
return cell;
}
else {
// Nothing
}
//cell.textLabel.text = [UIAppDelegate.youTubeUrlsArray objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
}
-(void)didButtonTouchUpInside:(id)sender{
UIButton *btn = (UIButton *) sender;
CGRect buttonFrameInTableView = [btn convertRect:btn.bounds toView:table];
NSIndexPath *indexPath = [table indexPathForRowAtPoint:buttonFrameInTableView.origin];
NSLog(#"%d",indexPath.row);
secView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 768, 960)];
secView.backgroundColor = [UIColor redColor];
[self.view addSubview:secView];
NSURL* url = [UIAppDelegate.videoUrlsArray objectAtIndex:indexPath.row];
// Now set up the movie player controller and play the movie.
player = [[MPMoviePlayerController alloc] initWithContentURL: url];
[[player view] setFrame: CGRectMake(0, 50, 768, 910)]; // frame must match parent view
[secView addSubview: [player view]];
[player play];
//btn_hideSecview = [UIButton buttonWithType:UIButtonTypeCustom];
btn_hideSecview =[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 45)];
btn_hideSecview.backgroundColor = [UIColor greenColor];
// btn_hideSecview.frame = CGRectMake(600, 0, 70, 45);
[btn_hideSecview setBackgroundColor:[UIColor whiteColor]];
[btn_hideSecview addTarget:self action:#selector(method_Hide_Secview) forControlEvents:UIControlEventTouchUpInside];
[secView addSubview:btn_hideSecview];
}
Any idea or suggestions would be highly welcome.
As I understand you have created "secView2" and "moviePlayer" as local properties, that means you use only one instance of these classes. For each invoke of table delegate method cellForRowAtIndexPath - create new object of MoviePlayer and UIView. If you need access outside of that delegate, prepare some DataSource NSMutableArray which will store that instances.
MPMoviePlayerController * newPlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
and
UIView *secView2 =[[UIView alloc]initWithFrame:CGRectMake(84,5,600,170)];

Table view button index cell

I have one table view in that cell is custom. I am adding two button on each cell of table view. when I click on first button at same time second button from same cell is changing its image. for that I have methods as editQuantity and Cancelorder. using #sel. I am getting an issue that when i click on first button insted of changing same cell another button its changing another cells button also when I scroll table view its losses all selected button
Here Is My Code--
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
simpleTableIdentifier = #"MenuNameCell";
MenuNameCell *cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell== nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
{
NSArray *arrayView = [cell.contentView subviews];
for (UIView *vTemp in arrayView)
{
[vTemp removeFromSuperview];
}
NSLog(#"---No New Cell hiiii");
// Setting Tag To UIButton
_checkButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
_cancelButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setTag:indexPath.row];
_checkButton.titleLabel.tag = indexPath.row;
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
// Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton setTag:indexPath.row];
_cancelButton.titleLabel.tag = indexPath.row;
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
// Adding All To Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
//objc_setAssociatedObject(_checkButton, iindex, indexPath,OBJC_ASSOCIATION_RETAIN );
return cell;
}
-(void)editQuantity:(id)sender{
button = (UIButton *)sender;
row = button.tag;
col = button.titleLabel.tag;
NSLog(#"Check Button index is %d",row);
NSLog(#"cehck title is %d",col);
_textFieldQuantity.userInteractionEnabled = YES;
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
The problem is that the default tag value for any control is set to 0 and you have used the _cancelButton.tag = 0;. Just change the value to 10 and then _cancelButton.tag = 1; change 1 to 11.
This will solve your problem :)
As I see _checkButton, _nameLabel, _amountMenu, _textFieldQuantity & _cancelButton all are instance variable of your view controller class.
In cellForRowAtIndexPath: as you are assigning new objects to all these, they will refere to objects of last cell displayed. Means all these will point to components from last cell.
Hence changing background images for _checkButton & _cancelButton will affect for buttons in last cell.
Also in cellForRowAtIndexPath: while creating these buttons, you are setting background image for them, hence after scrolling your button images are getting changed. Remember cellForRowAtIndexPath: gets called for a row each time that row becomes visible after getting hidden while scrolling.
You need to maintain state of buttons in separate array, so that you can reset state for buttons in cellForRowAtIndexPath: after dequeuing.

Cells display content from previous cells and sometime crashes

I have problem with a UITableview, I'm fetching some data and displaying it in a custom cell views, almost everything is going well except two issues :
When I scroll down, some new cells show content from previous cells (especially the TextView cellText)
sometime the app crashes with [UIImageView setText:]: unrecognized selector sent to instance at line :
[cellText setText:postText];
Here is my cellForRowAtIndexPath method :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *PostCellIdentifier;
Post *info = [posts objectAtIndex:indexPath.row];
NSString *PostType = info.type;
if([PostType isEqualToString:#"quote"]) {
PostCellIdentifier = #"NewsQuoteCell";
} else if([PostType isEqualToString:#"article"]) {
PostCellIdentifier = #"NewsArticleCell";
} else if([PostType isEqualToString:#"picture"]) {
PostCellIdentifier = #"NewsPictureCell";
} else if([PostType isEqualToString:#"video"]) {
PostCellIdentifier = #"NewsVideoCell";
} else if([PostType isEqualToString:#"audio"]) {
PostCellIdentifier = #"NewsAudioCell";
}
NewsQuoteCell *cell = [tableView dequeueReusableCellWithIdentifier:PostCellIdentifier];
if (cell == nil) {
cell = [[NewsQuoteCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PostCellIdentifier];
}
UILabel *cellLabel = (UILabel *)[cell.contentView viewWithTag:1];
[cellLabel setText:info.masjid_name];
UILabel *cellDate = (UILabel *)[cell.contentView viewWithTag:2];
[cellDate setText:info.date];
UITextView *cellText = (UITextView *)[cell.contentView viewWithTag:5];
NSString *postText = info.title;
[postText stringByDecodingHTMLEntities];
if ([postText length] > 300) {
postText = [postText substringToIndex:300];
postText = [postText stringByAppendingString:#"..."];
}
[cellText setText:postText];
CGRect frame = cellText.frame;
frame.size.height = cellText.contentSize.height;
cellText.frame = frame;
UIImageView *cellImage = (UIImageView *)[cell.contentView viewWithTag:3];
NSString *imagePath = info.masjid_thumb;
[cellImage setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#", imagePath]]];
cell.backgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"news_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 0, 10, 0)] ];
cell.selectedBackgroundView = [ [UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"news_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 0, 10, 0)] ];
if([PostType isEqualToString:#"article"]) {
cellText.userInteractionEnabled = YES;
UITapGestureRecognizer *pgrText = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTapArticle:)];
[cellText setTag:indexPath.row];
[cellText addGestureRecognizer:pgrText];
UIImageView *cellMedia = (UIImageView *)[cell.contentView viewWithTag:10];
cellMedia.userInteractionEnabled = YES;
UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTapArticle:)];
[cellMedia setTag:indexPath.row];
[cellMedia addGestureRecognizer:pgr];
} else if ([PostType isEqualToString:#"video"]) {
cellText.userInteractionEnabled = YES;
UITapGestureRecognizer *pgrText = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
[cellText setTag:indexPath.row];
[cellText addGestureRecognizer:pgrText];
UIImageView *cellMedia = (UIImageView *)[cell.contentView viewWithTag:10];
cellMedia.userInteractionEnabled = YES;
UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
[cellMedia setTag:indexPath.row];
[cellMedia addGestureRecognizer:pgr];
} else if ([PostType isEqualToString:#"audio"]) {
cellText.userInteractionEnabled = YES;
UITapGestureRecognizer *pgrText = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
[cellText setTag:indexPath.row];
[cellText addGestureRecognizer:pgrText];
UIImageView *cellMedia = (UIImageView *)[cell.contentView viewWithTag:10];
cellMedia.userInteractionEnabled = YES;
UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
[cellMedia setTag:indexPath.row];
[cellMedia addGestureRecognizer:pgr];
} else if ([PostType isEqualToString:#"picture"]) {
cellText.layer.shadowColor = [[UIColor blackColor] CGColor];
cellText.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
cellText.layer.shadowOpacity = 0.5f;
cellText.layer.shadowRadius = 0.5f;
UIImageView *cellMedia = (UIImageView *)[cell.contentView viewWithTag:7];
NSString *mediaPath = info.media;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:mediaPath]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *image) {
UIImage* scaled2 = [image scaleToFitSize:(CGSize){284, 284}];
[cellMedia setImage:scaled2];
CGRect frame1 = cellMedia.frame;
frame1.size.width = 284;
frame1.size.height = scaled2.size.height;
cellMedia.frame = frame1;
}];
[operation start];
cellMedia.userInteractionEnabled = YES;
UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTapPicture:)];
[cellMedia setTag:indexPath.row];
[cellMedia addGestureRecognizer:pgr];
if ([postText length] > 300) {
postText = [postText substringToIndex:300];
postText = [postText stringByAppendingString:#"..."];
}
[cellText setText:postText];
CGRect frame = cellText.frame;
frame.size.height = cellText.contentSize.height;
frame.origin.y = cellMedia.frame.origin.y + (cellMedia.frame.size.height - cellText.contentSize.height);
cellText.frame = frame;
}
return cell;
}
Any help please ?
It looks like you have a subclass of UITableViewCell called NewsQuoteCell. You can override the prepareForReuse method in the NewsQuoteCell class to fix your new cell shows content of previous cell issue. The other issue seemed to have to do with the your tag for view number 5 was not a UITextView but a UIImageView. I would double check your NewsQuoteCell's implementation file.
I assume you have created NewsQuoteCell in a seperate nib file. If thats the case why dont you setup proper IBOutlets to bind different components like the cellLabel, cellDate, cellText etc. That way you don't have to retrieve these components using viewWithTag.
And you are probably doing something funny with the tag. Have you setup the tags properly? One definite problem is your second error message. You are retrieving a UIImageView with the viewWithTag call and referencing it with UITextView. Make sure that tags are set up properly. And it never hurts to set the tag values to something unique, like 101, 102,103... etc.
Hope this helps.

Resources