SDWebImage not showing randomly in UITableViewCell - objective-c

Hello I have a script that downloads an image and dynamically sets the UITableView height after it finishes the download, but some images randomly do not show , the curious think is that when i change back and forth the tab the images suddenly appear . in the options argument i am passing SDWebImageRetryFailed.
Any idea would be more than welcome , thanks.
#interface NeobuggyFrontPageViewController()
{
UIImageView *adBanner;
NSArray *news ;
NSMutableData *imageData;
NSURLConnection *connection;
UIImage *neoImage;
NSString *category;
RSSItem *item;
FrontPageViewNewsCell *cell ;
CGRect newFrame;
__block CGRect descFrame;
float newWidth , newHeight;
__block float blockHeight;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
item = [news objectAtIndex:[indexPath row]];
cell = [tableView dequeueReusableCellWithIdentifier:#"FrontPageNewsCell"];
[[cell newsTitle] setText:[item title]];
[[cell newsVideo] setAlpha:0.0];
if ([item newsImageURL]){
descFrame = [[cell newsBody] frame];
[[cell newsImage] setImageWithURL:[item newsImageURL] placeholderImage:[UIImage imageNamed:#"placeholderImage.png"] options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
if (image) {
CGRect newsImageFrame = [[cell newsImage] frame];
float downImageWidth = image.size.width;
float downImageHeight = image.size.height;
float newsImageWidth = 304.00; //imageViewSize.size.width;
if (downImageWidth > newsImageWidth) {
float scaleFactor = newsImageWidth / downImageWidth;
newWidth = downImageWidth * scaleFactor;
newHeight = downImageHeight * scaleFactor;
} else {
newWidth = downImageWidth;
newHeight = downImageHeight;
}
newFrame = CGRectMake(newsImageFrame.origin.x, newsImageFrame.origin.y, newWidth, newHeight);
[[cell newsImage] setFrame:newFrame]; //asigno el nuevo frame a la imagen .
float newOriginY = newFrame.origin.y + newFrame.size.height + 10.00;
descFrame = CGRectMake(cell.newsBody.frame.origin.x,
newOriginY,
304.00,
cell.newsBody.frame.size.height);
blockHeight = newHeight;
}
NSLog(#"image %# cached ? %u", image ,cacheType);
if (error) {
NSLog(#"Error: %#",error);
}
}];
} else if([item newsVideoURL]) {
[[cell newsImage] setAlpha:0.0];
[[cell newsVideo] setAlpha:1.0];
[[cell newsVideo] loadRequest:[NSURLRequest requestWithURL:[item newsVideoURL]]];
float newOriginY = cell.newsVideo.frame.origin.y + cell.newsVideo.frame.size.height + 10.00;
descFrame = CGRectMake(cell.newsBody.frame.origin.x, newOriginY, 304, cell.newsBody.frame.size.height);
blockHeight = cell.newsVideo.frame.size.height;
}
[[cell newsImage] setNeedsDisplay];
NSString *desc = [[NSString alloc] initWithString:[item description]];
[[cell newsBody] setFrame:descFrame];
desc = [desc htmlToString:desc];
[[cell newsBody] setText:desc];
[[cell newsBody] setNumberOfLines:0];
[[cell newsBody] sizeToFit];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = (FrontPageViewNewsCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
CGSize descHeight = [[[cell newsBody] text] sizeWithFont:[[cell newsBody] font] constrainedToSize:cell.newsBody.frame.size lineBreakMode:[[cell newsBody] lineBreakMode]];
CGSize titleHeight = [[[cell newsTitle] text] sizeWithFont:[[cell newsTitle] font] constrainedToSize:cell.newsTitle.frame.size lineBreakMode:[[cell newsTitle] lineBreakMode]];
newHeight = cell.newsImage.frame.size.height;
if (blockHeight == 0) {
[tableView reloadData];
} else {
float ch = titleHeight.height + blockHeight + descHeight.height + 70;
[self setCellHeight:ch];
}
return _cellHeight;
}
Partially solved although solution less than ideal. Since i only needed to show 10 cells I prevented the reuse of the UITableViewCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
item = [news objectAtIndex:[indexPath row]];
NSString *identifier = [NSString stringWithFormat:#"Cell %d", indexPath.row];
UINib *nib = [UINib nibWithNibName:#"FrontPageViewNewsCell" bundle:nil];
[[self tableView] registerNib:nib forCellReuseIdentifier:identifier];
cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// cell = [tableView dequeueReusableCellWithIdentifier:#"FrontPageNewsCell"];
still interested in finding a solution reusing cell
Thanks,

Related

UITableView reloadData lose elements from cell

I have a UITableView and his datasource is an NSMutableArray declared in my interface:
#property (strong, nonatomic) NSMutableArray *arrElements;
Now I implemented a simple "load more" in this way:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
float endScrolling = scrollView.contentOffset.y + scrollView.frame.size.height;
if (endScrolling >= scrollView.contentSize.height)
{
//only if i have others results i will call load more
if([self.items_amount integerValue] > self.arrElements.count) {
if(DEBUG_MODE == 1) {
NSLog(#"Load more");
}
//get start param from array size and call load more
NSNumber *start = [NSNumber numberWithInteger:([self.arrElements count]+1)];
NSArray *passParams = [NSArray arrayWithObjects:self.menuItem,start,[NSNumber numberWithInteger:NUM_RESULTS_FOR_PAGE], nil];
[self performSelector:#selector(loadMore:) withObject:passParams afterDelay:0.1];
}
}
}
and this is my loadMore method:
//load more elements
- (void)loadMore:(NSArray *)arrParams {
//(MenuItem *)menuItem startingFrom:(NSNumber *)start numResults:(NSNumber *)results;
MenuItem *menuItem = [arrParams objectAtIndex:0];
NSNumber *start = [arrParams objectAtIndex:1];
NSNumber *results = [arrParams objectAtIndex:2];
if(DEBUG_MODE == 1) {
NSLog(#"Before load more %lu", (unsigned long)[self.arrElements count]);
}
//call API and parse it
WebServicesClient *restClient = [[WebServicesClient alloc] init];
NSData *data = [restClient callWorkAPI:[menuItem pathAPI] inLanguage:[[NSLocale preferredLanguages] objectAtIndex:0] withLat:self.latitude withLng:self.longitude startingFrom:start numRows:results];
for(Work* work in [[restClient parseWorks:data] objectForKey:#"items"]) {
[self.arrElements addObject:work];
}
if(DEBUG_MODE == 1) {
NSLog(#"After load more %lu", (unsigned long)[self.arrElements count]);
}
[self.tableElem reloadData];
}
And this is my custom cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier;
CellIdentifier = #"HomeCell";
HomeCell *cell = (HomeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell) {
cell = [[HomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Work *work = (Work *)[[self arrElements] objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.labelTitleItem.text = [work title];
cell.labelSubtitleItem.text = #"my category"
//if exists image
if([[work image] isKindOfClass:[NSString class]] && [[work image] length] > 0) {
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:[work image]]];
if ( data == nil )
return;
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageItem.image = [UIImage imageWithData: data];
});
});
} else {
//remove image setting height to 0
[cell.imageItem setFrame:CGRectMake(cell.imageItem.frame.origin.x, cell.imageItem.frame.origin.y, cell.imageItem.frame.size.width, 0)];
}
if([[work distance] isKindOfClass:[NSString class]]) {
[cell.imagePriority setBackgroundColor:[UIColor lightGrayColor]];
cell.labelDistanceItem.text = [self convertDistance:[work distance]];
cell.labelDistanceItem.textColor = [UIColor whiteColor];
} else {
//remove image setting height to 0
[cell.imagePriority setFrame:CGRectMake(cell.imagePriority.frame.origin.x, cell.imagePriority.frame.origin.y, cell.imagePriority.frame.size.width, 0)];
//remove label distance setting height to 0
[cell.labelSubtitleItem setFrame:CGRectMake(cell.labelSubtitleItem.frame.origin.x, cell.labelSubtitleItem.frame.origin.y, cell.labelSubtitleItem.frame.size.width, 0)];
}
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self arrElements] count];
}
Now the problem is that after reloadData i lose the text of a UILabel (my category) of my CustomCell
please, Any suggests?
I've had similar problems with TalbeViews. Try using the method
- (void) tableView:(UITableView *)tableView willDisplayCell:(RCGameTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
to add the elements that you want. Keep the cell initialization that you do at the beginning of cellForRowAtIndexPath, but then return the cell right after and set the background color, labels, images, etc. in the willDisplayCell delegate function I mentioned.

Adjust height UITableViewCell after cellForRowAtIndexPath

I can't set the height of my UITableViewCell according to my constrains.
I have in each cell on my UITableView a UILabel where the height is not fixed and depends of the height of this UILabel.
I tried to set the frame on the cell after I update the label's content but nothing happens. Please find my code below:
//On my controller
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CommentCell";
CommentCell *commentCell = [tView dequeueReusableCellWithIdentifier:CellIdentifier];
if (commentCell == nil) {
commentCell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Comment *comment;
if (commentsArray.count > indexPath.row) {
comment = [commentsArray objectAtIndex:indexPath.row];
}
[commentCell setComment:comment];
[commentCell setCommonFields];
currentCellheight = commentCell.contentLabel.frame.size.height + 40;
DDLogInfo(#"Current Cell Height: %f", currentCellheight);
return commentCell;
}
//On my custom Cell (CommentCell.m)
-(void)setCommonFields {
if (self.comment != nil) {
self.contentLabel.text = self.comment.content;
self.contentLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(self.contentLabel.frame.size.width, FLT_MAX);
CGRect expectedLabelRect = [self.contentLabel.text boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
CGRect newFrame = self.contentLabel.frame;
newFrame.size.height = expectedLabelRect.size.height;
self.contentLabel.frame = newFrame;
}
}
I tried also to set the height thanks to the heightForRowAtIndexPath method but this method is called before cellForRowAtIndexPath where my label is updated.
I don't have much more idea to solve this problem.
Thank you in advance.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"indexPath.row :%ld",(long)indexPath.row);
CGSize contsize={260.00f,3000.00f};
UIFont *font=[UIFont fontWithName:#"Helvetica-Bold" size:15.0];
NSString *strt11=#"hellllllooooooooooooooooooo hellllllooooooooooooooooooo hellllllooooooooooooooooooo";
CGSize fontSize=[strt11 sizeWithFont:font constrainedToSize:contsize lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"fontSize indexPath :%f",fontSize.height);
if (fontSize.height>22)
return fontSize.height+50.0f;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"reuse"];
if(cell==nil)
{
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"reuse"];
UILabel *lblcomment=[[UILabel alloc] initWithFrame:CGRectMake(55,23, 160,20)];
[lblcomment setBackgroundColor:[UIColor clearColor]];
[lblcomment setTag:72];
[lblcomment setTextColor:[UIColor grayColor]];
[lblcomment setNumberOfLines:0];
[lblcomment setFont:[UIFont fontWithName:#"Helvetica" size:15.0]];
[lblcomment setText:#"Its rude day on goin...Its rude day on goin...Its rude day on goin..."];
[cell addSubview:lblcomment];
}
UILabel *lblcomment=(UILabel *)[cell viewWithTag:72];
CGSize contsize={260.00f,3000.00f};
UIFont *font=[UIFont fontWithName:#"Helvetica-Bold" size:15.0];
NSString *strt11=#"hellllllooooooooooooooooooo hellllllooooooooooooooooooo hellllllooooooooooooooooooo";
CGSize fontSize=[strt11 sizeWithFont:font constrainedToSize:contsize lineBreakMode:NSLineBreakByWordWrapping];
float h=20;
NSLog(#"re %f",fontSize.height);
if (fontSize.height>22.0f){
h=fontSize.height+7.0;
NSLog(#"heigtaaaaa %f",h);
}
[lblcomment setFrame:CGRectMake(55,23,260,h)];
NSString *strDecodeComment=#""hellllllooooooooooooooooooo hellllllooooooooooooooooooo hellllllooooooooooooooooooo";
[lblcomment setText:strDecodeComment];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
Thanks to Rohit's answer, please find my working code:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *content=((Comment *)[commentsArray objectAtIndex:indexPath.row]).content;
CGSize maximumLabelSize = CGSizeMake(234.00f, FLT_MAX);
CGRect expectedLabelRect = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
if (expectedLabelRect.size.height > 41) {
return expectedLabelRect.size.height + 81;
}
else
return 81;
}

Changing the size of a UITableViewCell based on the size of a subview

How can I scale UITableViewCells based on the amount of content in them? In my cells I use three labels which represent a forum. The labels are named "alias", "date", and "comments". The third label, comments, can be any number of rows. Therefore, I need my cells to become dynamically size, depending on the amount of text in the "comments" label. Here is my code:
- (BOOL)textFieldShouldReturn:(UITextField *)pTextField
{
[self setLoadingState:YES];
[pTextField resignFirstResponder];
NSUserDefaults *userStorage = [NSUserDefaults standardUserDefaults];
NSString *alias = [self urlEncode:[userStorage objectForKey:#"alias"]];
NSString *email = [self urlEncode:[userStorage objectForKey:#"email"]];
NSString *who = [self getUniqueDeviceId];
NSString *comment = [self urlEncode:[pTextField text]];
comment = [comment stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
who = [who stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([self isBlank:comment])
{
[self setLoadingState:NO];
pTextField.text = #"";
return NO;
}
if([self isBlank:alias])
{
[self showMessagePopup:NSLocalizedString(#"MessageMustChooseAlias", nil)];
return NO;
}
[self.forumThreadDataProvider startSendPost:self.taskId : self.forumThreadId : alias : who : email : comment];
pTextField.text = #"";
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Feedback *item = [self.items objectAtIndex:indexPath.row];
UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];
[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];
commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];
return cell;
}
Ive tryed already myself with the following code-example but it failed big-TIME:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell) {
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
return commentLabel.frame.size.height;
}
else
return 30;
}
Check this tutorial for how to set dynamically set cell height,
Basically you need to use methods like this to calculate the height of Laebl,
- (CGFloat)RAD_textHeightForSystemFontOfSize:(CGFloat)size {
//Calculate the expected size based on the font and linebreak mode of the label
CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width - 50;
CGFloat maxHeight = 9999;
CGSize maximumLabelSize = CGSizeMake(maxWidth,maxHeight);
CGSize expectedLabelSize = [self sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];
return expectedLabelSize.height;
}
Then you need to implement the heightForRowAtIndexPath method,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *label = [self.aNote length] == 0 ? kDefaultNoteLabel : self.aNote;
CGFloat height = [label RAD_textHeightForSystemFontOfSize:kTextViewFontSize] + 20.0;
return height;
}

cell specification in uitableview [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
UITableView create 4 square
I want to have 4 cell in one row in uiTableview but nothing appear, I don't know why would you please help me
this a the picture for cell
Thanks in advance
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *monKey = #"Monday";
NSString *tueKey = #"Tuesday";
NSString *wedKey = #"Wednday";
NSString *thuKey = #"Thusday";
NSString *friKey = #"Friday";
NSString *satKey = #"Satuarday";
NSString *sunKey = #"Sunnday";
[contents setObject:[NSArray arrayWithObjects:#"Work Time", #"Absence", nil] forKey:monKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", #"Absence", nil] forKey:wedKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", nil] forKey:tueKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", nil] forKey:thuKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", nil] forKey:friKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", nil] forKey:satKey];
[contents setObject:[NSArray arrayWithObjects:#"Compensation", #"Work Time", nil] forKey:sunKey];
[keys addObject:tueKey];
[keys addObject:monKey];
[keys addObject:wedKey];
[keys addObject:thuKey];
[keys addObject:friKey];
[keys addObject:satKey];
[keys addObject:sunKey];
[self setSectionKeys:keys];
[self setSectionContents:contents];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self action:#selector(addNewItem)];
self.navigationItem.rightBarButtonItem = rightButton;
}
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int column = 4;
for (int i=0; i<column; i++) {
UIImageView *aBackgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(32+184*i,10, 167,215)];
aBackgroundImageView.tag = (column*indexPath.row)+i;
[cell.contentView addSubview:aBackgroundImageView];
// [aBackgroundImageView release];
}
return cell;
}
Edit 1
this is the picture when I added this line
aBackgroundImageView.backgroundColor = [UIColor redColor];
Edit 2 :
with Rog method
It seems to me that in:
for (int i=0; i<column; i++) {
UIImageView *aBackgroundImageView = [[UIImageView alloc]initWithFrame:CGRectMake(32+184*i,10, 167,215)];
aBackgroundImageView.tag = (column*indexPath.row)+i;
[cell.contentView addSubview:aBackgroundImageView];
// [aBackgroundImageView release];
}
you are not providing a content for your views...
so that should explain why you don't see anything... Try adding:
aBackgroundImageView.backgroundColor = [UIColor redColor];
and see if anything changes.
Here i create the one demo application like you want and that some of the code put into here.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSUInteger devide=[self.tableArray count] / 3;
if ([self.tableArray count] % 3 >0 ) {
devide+=1;
} else {
devide=devide;
}
return devide;
}
And cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell==nil){
cell=[[[NSBundle mainBundle] loadNibNamed:#"CCell" owner:self options:nil] objectAtIndex:0];
UIButton *imgV1=(UIButton*)[cell viewWithTag:1];
UIButton *imgV2=(UIButton*)[cell viewWithTag:2];
UIButton *imgV3=(UIButton*)[cell viewWithTag:3];
[imgV1 addTarget:self action:#selector(btnTapped:) forControlEvents:UIControlEventTouchDown];
[imgV2 addTarget:self action:#selector(btnTapped:) forControlEvents:UIControlEventTouchDown];
[imgV3 addTarget:self action:#selector(btnTapped:) forControlEvents:UIControlEventTouchDown];
HJManagedImageV *img1=[[HJManagedImageV alloc] initWithFrame:CGRectMake(0, 0, imgV1.frame.size.width, imgV1.frame.size.height)];
HJManagedImageV *img2=[[HJManagedImageV alloc] initWithFrame:CGRectMake(0, 0, imgV2.frame.size.width, imgV2.frame.size.height)];
HJManagedImageV *img3=[[HJManagedImageV alloc] initWithFrame:CGRectMake(0, 0, imgV3.frame.size.width, imgV3.frame.size.height)];
img1.tag=img2.tag=img3.tag=10000;
img1.backgroundColor=img2.backgroundColor=img3.backgroundColor=[UIColor clearColor];
[imgV1 addSubview:img1];
[imgV2 addSubview:img2];
[imgV3 addSubview:img3];
}
int x=indexPath.row;
x=x*3;
UIButton *imgV1=(UIButton*)[cell viewWithTag:1];
UIButton *imgV2=(UIButton*)[cell viewWithTag:2];
UIButton *imgV3=(UIButton*)[cell viewWithTag:3];
HJManagedImageV *img1=(HJManagedImageV*)[imgV1 viewWithTag:10000];
HJManagedImageV *img2=(HJManagedImageV*)[imgV2 viewWithTag:10000];
HJManagedImageV *img3=(HJManagedImageV*)[imgV3 viewWithTag:10000];
[img1 clear];
[img2 clear];
[img3 clear];
[imgV1 setTitle:[self.tableArray objectAtIndex:x] forState:UIControlStateDisabled];
img1.url=[NSURL URLWithString:[self.tableArray objectAtIndex:x]];
[img1 showLoadingWheel];
[GlobalCacheManager manage:img1];
if((x+1) >= self.tableArray.count){
imgV2.hidden=imgV3.hidden=YES;
[imgV2 setBackgroundImage:nil forState:UIControlStateNormal];
[imgV3 setBackgroundImage:nil forState:UIControlStateNormal];
} else if( (x+2)>=self.tableArray.count) {
img2.url=[NSURL URLWithString:[self.tableArray objectAtIndex:x+1]];
[img2 showLoadingWheel];
[GlobalCacheManager manage:img2];
imgV1.hidden=imgV2.hidden=YES;
imgV3.hidden=YES;
[imgV2 setTitle:[self.tableArray objectAtIndex:x+1] forState:UIControlStateDisabled];
[imgV3 setBackgroundImage:nil forState:UIControlStateNormal];
} else {
[img2 showLoadingWheel];
[img3 showLoadingWheel];
img2.url=[NSURL URLWithString:[self.tableArray objectAtIndex:x+1]];
[GlobalCacheManager manage:img2];
img3.url=[NSURL URLWithString:[self.tableArray objectAtIndex:x+2]];
[GlobalCacheManager manage:img3];
imgV2.hidden=imgV3.hidden=NO;
[imgV2 setTitle:[self.tableArray objectAtIndex:x+1] forState:UIControlStateDisabled];
[imgV3 setTitle:[self.tableArray objectAtIndex:x+2] forState:UIControlStateDisabled];
}
return cell;
}
Your method is a bit of a mess. Your main problem is how you are setting the frame origin for the UIImageView instances as they are 1) too big for the cell 2) out of the cell bounds.
Try this (ps: there may be typos as I've written it off the top of my head):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
int numberOfColumns = 4;
CGSize gridSize = CGSizeMake(cell.contentView.frame.size.width / numberOfColumns, cell.contentView.frame.size.height / 2); // Height size is arbitrary here, width is obtained by dividing total width by number of columns
for (int i=0; i < column; i++)
{
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(gridSize.width * i, cell.contentView.frame.size.height/2 - gridSize.height/2, gridSize.width, gridSize.height)];
aview.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1/i+1]; // This is just so you can see the different gridCells within the cell
[cell.contentView addSubview:aView];
[aView release];
}
return cell;
}

Single row selection - UITableView

Good Afternoon,
I'm trying to deploy my application in the selection of a single line in UITableView, but when I select another row, the previous line is not clear. I'm using images to represent the selection of the lines. I've tried to make each user's selection table rows stay with the image of deselection, but got no success.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *EditCellIdentifier = #"EditCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:EditCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:EditCellIdentifier] autorelease];
UILabel *label = [[UILabel alloc] initWithFrame:kLabelRect];
label.tag = kCellLabelTag;
[cell.contentView addSubview:label];
[label release];
UIImageView *imageView = [[UIImageView alloc] initWithImage:unselectedImage];
imageView.frame = CGRectMake(5.0, 10.0, 23.0, 23.0);
[cell.contentView addSubview:imageView];
imageView.hidden = !inPseudoEditMode;
imageView.tag = kCellImageViewTag;
[imageView release];
}
[UIView beginAnimations:#"cell shift" context:nil];
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kCellImageViewTag];
NSNumber *selected = [selectedArray objectAtIndex:[indexPath row]];
imageView.image = ([selected boolValue]) ? selectedImage : unselectedImage;
imageView.hidden = !inPseudoEditMode;
[UIView commitAnimations];
UILabel *label = (UILabel *)[cell.contentView viewWithTag:kCellLabelTag];
label.text =[listOfItems objectAtIndex:[indexPath row]];
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
label.opaque = NO;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tv deselectRowAtIndexPath:indexPath animated:YES];
if (inPseudoEditMode) {
BOOL selected = [[selectedArray objectAtIndex:[indexPath row]] boolValue];
[selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:!selected]];
[tv reloadData];
}
}
I guess you want to allow only one row selected at a time.
Here is what I suggest in tableView: didSelectRowAtIndexPath::
Mark all row as not selected:
for (int i = 0; i < [selectedArray count]; i++) {
[selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
Then, mark the current row as selected:
[selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:YES]];
OR, do it all in the same for loop:
for (int i = 0; i < [selectedArray count]; i++) {
NSNumber rowSelected = [NSNumber numberWithBool:(indexPath.row == i)];
[selectedArray replaceObjectAtIndex:i withObject:rowSelected];
}
Hope this is what you want!
Shortest way which i use
for (int i = 0; i < [selectedArray count]; i++) {
[selectedArray replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:i==indexpath.row?YES:NO]];
}