i'm trying to reposition a UILabel inside my custom UICollectionViewCell with nib.
The problem iss , that at the start, only the first item's subviews looks as it should (positioned by code), and all the other items subviews are positioned like the nib.
if i scroll back and forth a few times, it loads all the other items OK as well.
I tried with and without AutoLayout as well as stated in some answers HERE and tried setting / removing Constrains as told here
Loosing my mind, any help will be great!
in my FeedCell i did this:
-(void)layoutSubviews{
[super layoutSubviews];
[self sortViews];
}
- (void) sortViews{
[_fromLable sizeToFit];
[_toLable sizeToFit];
[_fromYearLabel sizeToFit];
[_dashLabel sizeToFit];
[_dashLabel centerHorizontalInParent];
// rotate the year labels
[_fromYearLabel setTransform:CGAffineTransformMakeRotation(M_PI / 2)];
[_toLable setX:[_dashLabel x] + [_dashLabel width] + 15 ];
[_fromYearLabel setX:[_dashLabel x] - [_fromYearLabel width] - 15 ];
}
I tried calling [cell setNeedsDisplay] in cellForItemAtIndexPath and also in willDisplayCell:forItemAtIndexPath
My cell is dequeue in the cellForItemAtIndexPath like this:
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
FeedCell *cell= (FeedCell*)[collectionView dequeueReusableCellWithReuseIdentifier:#"FeedCell" forIndexPath:indexPath];
NSDictionary *feed = [_datasource objectAtIndex:indexPath.row];
if (feed) {
[cell.mediaImage setHidden:NO];
NSString* desc = [feed objectForKey:#"desc"];
if(desc){
cell.descriptionTextview.text = desc;
[cell.descriptionTextview adjustFontSizeToFillItsContentWithMaxFontSize:80 andMinValue:8 WithFont:fMyriadProRegular];
[cell.descriptionTextview setHidden:NO];
}
else
[cell.descriptionTextview setHidden:YES];
if ([feed objectForKey:#"title"]) {
cell.titleLabel.text = [feed objectForKey:#"title"];
}
if ([feed objectForKey:#"place"]) {
cell.placeLabel.text = [feed objectForKey:#"place"];
}
if ([feed objectForKey:#"location"]) {
[cell.locationLable setHidden:NO];
cell.locationLable.text = [feed objectForKey:#"location"];
}else{
[cell.locationLable setHidden:YES];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
NSInteger yearStart = 0;
NSInteger yearend = 0;
NSInteger totalYears = 0;
if ([feed objectForKey:#"startTime"]) {
NSString* startTime = [feed objectForKey:#"startTime"];
dateFromString = [dateFormatter dateFromString:startTime];
cell.fromLable.text = [dateFromString monthStringWithLength:3 capital:YES];
yearStart = [dateFromString year];
}
if ([feed objectForKey:#"endTime"]) {
NSString* endTime = [feed objectForKey:#"endTime"];
dateFromString = [dateFormatter dateFromString:endTime];
cell.toLable.text = [dateFromString monthStringWithLength:3 capital:YES];
yearend = [dateFromString year];
}
if (yearStart == 0 && yearend == 0) {
[cell.totalYears setHidden:YES];
}else if (yearStart > 0 && yearend == 0){
[cell.totalYears setHidden:NO];
totalYears = [[NSDate date] year] - yearStart;
}else{
[cell.totalYears setHidden:NO];
totalYears = yearend - yearStart;
}
cell.fromYearLabel.text = stringWithFormat(#"%zd", yearStart);
cell.totalYears.text = stringWithFormat(#"(%zd YEARS)", totalYears);
[cell.mediaImage setImageWithURL:[NSURL URLWithString:getImageUrlwithIdAndSize([[[_datasource objectAtIndex:indexPath.row] objectForKey:#"media"] objectAtIndex:0], 1)]];
}
cell.backgroundColor= [UIColor whiteColor];
[cell setNeedsDisplay];
return cell;
}
Try the following code:
(void)awakeFromNib
{
[super awakeFromNib];
self.contentView.frame = self.bounds;
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
Related
I want self.agendaTable to run reloadData when the calendarDidDateSelected runs, but that doesn't seem to happen. As far as I can tell, the table is setup properly, and I have it set to update the contents of self.agendaTableArray in cellForRowAtIndexPath when it reloads. What am I doing wrong?
I'm setting up the table like so:
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up Day Agenda table
CGRect frame = CGRectMake(0,380,self.view.frame.size.width,self.view.frame.size.height);
UITableView *agendaTable = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
agendaTable.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
agendaTable.delegate = self;
agendaTable.dataSource = self;
[agendaTable reloadData];
[self.view addSubview:agendaTable];
/////
self.agendaTableArray = [[NSArray alloc] init];
self.agendaTableArray = #[#"No events today!"];
[self.calendar setMenuMonthsView:self.calendarMenuView];
[self.calendar setContentView:self.calendarContentView];
[self.calendar setDataSource:self];
}
Relevant cellForRowAtIndexPath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
///...earlier code snipped for brevity
// title of the item
if (self.datePicked == [NSNumber numberWithInt:16]) {
NSLog(#"cellForRowAtIndexPath says self.datePicked is 16");
self.agendaTableArray = #[#"Dinner with Rebekah", #"Meeting with John"];
}
else {
self.agendaTableArray = #[#"No events today!"];
}
cell.textLabel.text = self.agendaTableArray[indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:14];
return cell;
}
calling calendarDidDateSelected like so:
- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date
{
NSLog(#"Date: %#", date);
// NSDateFormatter is used to create a date from a string
// static keyword is used to avoid create a new instance each time calendarDidDateSelected is called
static NSDateFormatter *dateFormatter = nil;
if(!dateFormatter){
dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"yyyy-MM-dd"; // Read the documentation for dateFormat
}
// If date picked is June 16th
NSDate *juneSixteenth = [dateFormatter dateFromString:#"2015-06-16"];
if([juneSixteenth compare:date] == NSOrderedSame){
self.datePicked = [NSNumber numberWithInt:16];
NSLog(#"self.datePicked: %#", self.datePicked);
}
[self.agendaTable reloadData];
}
Are you properly assigning your agendaTable you created to your 'agendaTable' property in your viewDidLoad?
self.agendaTable = agendaTable;
I'm thinking that this is an issue with reusing cells but I can't figure this out and would appreciate some additional eyes on it. I have a uitableviewcell subclass that compares two values, if one value is higher it changes the cell background to red, else it changes it to white. As I scroll, some cells are white that should be red and vice versa.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
tut_MaintListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"maintCell" forIndexPath:indexPath];
// Configure the cell...
MaintItem *mItem = [self.fetchedResultsController objectAtIndexPath:indexPath];
[cell configureCellForEntry:mItem sendCar:self.carDetail];
return cell;
}
UITableViewCell Subclass
- (void)configureCellForEntry:(MaintItem *)mItem sendCar:(Car *)carDetails
{
self.itemLabel.text = [mItem valueForKey:#"item"];
self.actionLabel.text = [mItem valueForKey:#"action"];
self.engineLabel.text = [mItem valueForKey:#"engineCode"];
self.maintIDLabel.text = [[mItem valueForKey:#"maintID" ]stringValue];
// Grab the mileages recorded in the log for this maint item and turn it into a sorted array
NSArray *result = [[mItem.toLog valueForKey:#"mileage"] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"" ascending:YES]]];
// Determine mileage of next service
NSString *nextServiceMileage = [NSString stringWithFormat:#"%d", [mItem.intMileage intValue] + [[result lastObject] intValue]];
nextServiceMileageNS = #([nextServiceMileage intValue]);
if ([mItem.frequencyID isEqualToNumber:[NSNumber numberWithInt:3]])
{
NSString *timing = [[NSString alloc] initWithFormat:#" %# Once at %# miles or %# months", [mItem valueForKeyPath:#"frequencyID"], [mItem valueForKeyPath:#"intMileage"], [mItem valueForKeyPath:#"intMonth"]];
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", timing];
self.howOftenLabel.text = howOften;
if (carDetails.mileage > nextServiceMileageNS)
{
self.backgroundColor = [UIColor redColor];
}
else
{
self.backgroundColor = [UIColor whiteColor];
}
}
else if ([mItem.frequencyID isEqualToNumber:[NSNumber numberWithInt:4]])
{
NSString *timing = [[NSString alloc] initWithFormat:#" %# Every %# miles or %# months, due at %# ", [mItem valueForKeyPath:#"frequencyID"], [mItem valueForKeyPath:#"intMileage"], [mItem valueForKeyPath:#"intMonth"], nextServiceMileage];
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", timing];
self.howOftenLabel.text = howOften;
if (carDetails.mileage > nextServiceMileageNS)
{
self.backgroundColor = [UIColor redColor];
}
else
{
self.backgroundColor = [UIColor whiteColor];
}
}
else
{
NSString *howOften = [[NSString alloc] initWithFormat:#" %#", [mItem valueForKeyPath:#"frequencyID"]];
self.howOftenLabel.text = howOften;
}
}
The Solution is: you have to set the backgroundColor in the else part too. Better solution would be,
UIView *backgroundView;
if (condition_1) {
backgroundView = [UIView new];
[backgroundView setBackgroundColor:[UIColor whiteColor]];
} else if (condition_2) {
backgroundView = [UIView new];
[backgroundView setBackgroundColor:[UIColor redColor]];
} else {
// here you can set or leave it.
}
[self setBackgroundView:backgroundView];
hope it will work for you...
The solution was that I was comparing two NSnumber objects in the if statement. I changed
if (carDetails.mileage > nextServiceMileageNS)to if ([carDetails.mileage intvalue] > [nextServiceMileageNS intvalue]) and now it worked correctly. The way the random background were applied it seemed to be a cell reuse issue.
in my tableview I have a button in the custom cell
I used the delegates to take an action to the button
The button image changes only on the selected cell
My problem is this:
When I press the button happens:
the selected cell is working properly and the button changes correctly (correct)
the second immediately after the selected cell does not change the button (corrected)
the third cell repeats the action of the selected cell (wrong)
This is repeated endlessly do not understand why
The button should change only the selected cell and not on other non-selected
Can you help me please?
-(void)ButtonPressedGoPoint:(FFCustomCellWithImage *)custom button:(UIButton *)gopointpressed {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"it_IT"]];
NSNumber *likeCount = [numberFormatter numberFromString:custom.CountGoPoint.text];
if (!custom.AddGoPoint.selected) {
NSLog(#"TastoSelezionato");
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
}
else {
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
custom.CountGoPoint.text = [NSString stringWithFormat:#"%#", likeCount];
}
NSLog(#"TastoDeselezionato");
[custom.AddGoPoint setBackgroundImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
custom.AddGoPoint.selected = !custom.AddGoPoint.selected;
}
This is my implementation of the tableview
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.PostDetails = [ArrayforPost objectAtIndex:indexPath.row];
static NSString *IdentificazioneCellaIMG = #"CellaIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IdentificazioneCellaIMG ];
}
CellaIMG.delegate = self;
CellaIMG.tag = indexPath.row;
[CellaIMG.AddGoPoint setTag:indexPath.row];
if ([self AssignedGoPointToPost:self.PostDetails]) {
CellaIMG.AddGoPoint.selected =YES;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_Medal_Blu"] forState:UIControlStateNormal];
} else {
CellaIMG.AddGoPoint.selected =NO;
[CellaIMG.AddGoPoint setImage:[UIImage imageNamed:#"FFIMG_MedalADD"] forState:UIControlStateNormal];
}
NSString *FotoPostSocial = [self.PostDetails objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.FotoPost.layer.masksToBounds = YES;
CellaIMG.FotoPost.layer.cornerRadius = 2.0f;
CellaIMG.FotoPost.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.backgroundCell.layer.masksToBounds = YES;
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.LeggiCommentoButton.layer.cornerRadius = 2.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 25.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [self.PostDetails objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSString *NomeUser = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[self.PostDetails objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel); }
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 65);
}
return CellaIMG;
}
}
My app is scrolling and Searching very slow when I have Images set for each cell.Pictures lifted faster, but still slow when searching. Here is my code in the cell at row. Any ideas?
#interface UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size;
#end
#implementation UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#end
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSInteger buton1_tag = 100;
static NSInteger buton2_tag = 101;
if (indexPath.section == 0) {
CellIdentifier = #"CellMuzikEkle";
}else{
if(indexPath.row == 0 && !self.editing)
CellIdentifier = #"CellPlayereEkle";
else
CellIdentifier = #"CellDizi";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
if (indexPath.section == 1 && indexPath.row == 0 && !self.editing) // Grubu ekle
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell4" owner:self options:nil] objectAtIndex:0];
else{
if (indexPath.section == 0) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil] objectAtIndex:5];
UIButton *ipodbuton = (UIButton *) [cell.contentView viewWithTag:buton1_tag];
[ipodbuton addTarget:self action:#selector(iPoddan_Ekle:) forControlEvents:UIControlEventTouchUpInside];
UIButton *yuklenenler = (UIButton *) [cell.contentView viewWithTag:buton2_tag];
[yuklenenler addTarget:self action:#selector(Yuklenenlerden_Ekle:) forControlEvents:UIControlEventTouchUpInside];
}else{
cell.textLabel.font = [UIFont boldSystemFontOfSize:15.0];
cell.textLabel.numberOfLines=2;
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
[cell.imageView.layer setBorderWidth: 1.5];
}
}
}
if (indexPath.section == 1 && !self.editing && indexPath.row != 0)
cell.accessoryType =UITableViewCellAccessoryDetailDisclosureButton;
else
cell.accessoryType =UITableViewCellAccessoryNone;
if(indexPath.section == 0){
cell.textLabel.text = #"";
cell.detailTextLabel.text = #"";
cell.imageView.image = nil;
}else{
if (indexPath.row > 0 || self.editing) {
if (!self.editing)
indexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section];
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ? [[NSArray alloc] initWithArray:self.filteredListContent] : [[NSArray alloc] initWithArray:self.dizi];
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]] imageScaledToSize:CGSizeMake(65, 50)];
else
cell.imageView.image = nil;
cell.textLabel.text = [[aradizi objectAtIndex:indexPath.row] objectForKey:isim_s];
NSTimeInterval theTimeInterval = [[[aradizi objectAtIndex:indexPath.row] objectForKey:sure_s] intValue] - 1;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date1;
if (theTimeInterval >= 3600) {
[dateFormatter setDateFormat:#"HH:mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00:00"];
}else{
[dateFormatter setDateFormat:#"mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00"];
}
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
cell.detailTextLabel.text = [dateFormatter stringFromDate:date2];
}else{
if (tableView == self.searchDisplayController.searchResultsTableView)
cell.textLabel.text = AramaSonuclrPlayerEkle_lclz;
else
cell.textLabel.text = GrubuPlayereEkle_lclz;
}
}
return cell;
}
Resim_Artwork
- (UIImage *)Resim_Artwork:(NSDictionary *)dictr{
if ([dictr objectForKey:videoid_s]) {
if ([self Dosya_Varmi:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]])
return [UIImage imageWithContentsOfFile:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]];
}else{
if ([[[dictr objectForKey:urlsi_s] pathExtension] isEqualToString:#"mp4"]) {
AVURLAsset *assetresim = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:assetresim];
gen.appliesPreferredTrackTransform = YES;
int suresi = CMTimeGetSeconds(assetresim.duration);
if (suresi > 0) {
CMTime time;
if (suresi>6)
time = CMTimeMakeWithSeconds(6.0, 600);
else
time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return thumb;
}
}else {
if ([dictr objectForKey:kaynak_s]) {
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[dictr objectForKey:urlsi_s]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}else{
if ([self Dosya_Varmi:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]]){
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}
}
}
}
return [self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6];
}
tableView willDisplayCell
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *viewControllers = [self.tabBarController viewControllers];
NSArray *viewControllers2 = [[viewControllers objectAtIndex:0] viewControllers];
Player *detailViewController = (Player *)[viewControllers2 objectAtIndex:0];
[detailViewController.temalar Cell_Tema:cell];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [detailViewController.temalar Baslik_Renk];
cell.detailTextLabel.textColor = [detailViewController.temalar Bilgi_Renk];
[cell.imageView.layer setBorderColor: [tableView.separatorColor CGColor]];
[((UIButton *) [cell.contentView viewWithTag:100]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:100]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
}
Here:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
[[NSArray alloc] initWithArray:self.filteredListContent] :
[[NSArray alloc] initWithArray:self.dizi];
You should avoid creating objects inside cellForRowAtIndexPath wherever possible.
Anyway you don't need to:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
self.filteredListContent :
self.dizi;
Here you seem to be creating and resizing thumbnails on the fly. :
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
This is bound to jam up smooth tableView scolling. All of these should be pre-processed and cached, or at least only processed once here and cached for reuse.
Time-consuming nonUI processing like this can go onto another thread so that your scolling stays smooth even if the image isn't ready to show. Something like…
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image =
[[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell]){
cell.imageView.image = image;
}
});
});
else
cell.imageView.image = nil;
Regarding the date formatter: these are heavyweight objects, you need to ensure to only create once, keep in a property for reuse. I suggest you do the following:
Declare two date formatter properties and another for your zero'd date. Initialise them all in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.hoursFormat = [[NSDateFormatter alloc] init];
[self.hoursFormat setDateFormat:#"HH:mm:ss"];
self.minsFormat = [[NSDateFormatter alloc]init];
[self.minsFormat setDateFormat:#"mm:ss"];
self.zeroDate = [self.hoursFormat dateFromString:#"00:00:00"];
}
Then in cellForRowAtIndexPath:
NSDate* date = [self.zeroDate dateByAddingTimeInterval:theTimeInterval];
if (theTimeInterval >= 3600) {
self.label.text = [self.hoursFormat stringFromDate:date];
} else {
self.label.text = [self.minsFormat stringFromDate:date];
}
He Was, Thank you for the answer. performance was very nice. But since I made this change, the program closes.
new codes:
NSMutableArray *aradizi;
if (tableView == self.searchDisplayController.searchResultsTableView)
aradizi = self.filteredListContent;
if (indexPath.section == 2 && tableView != self.searchDisplayController.searchResultsTableView)
aradizi = self.dizi_klasorler;
if (indexPath.section == 3)
aradizi = self.dizi_veriler;
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s]){
if (cell.imageView.image == nil)
cell.imageView.image = [[self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image = [[self Resim_Artwork:[[aradizi objectAtIndex:indexPath.row] objectForKey:urlsi_s]] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if (tableView == self.searchDisplayController.searchResultsTableView){
if ([[self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}else{
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}
});
});
}else
cell.imageView.image = nil;
http://img29.imageshack.us/img29/1083/ekranresmi2013020301553.png
http://img502.imageshack.us/img502/5591/ekranresmi2013012919525.png
I update the table view cell using the method below:
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithIndexPath:(NSIndexPath *)indexPath
{
NSArray *arr = [self.tableView indexPathsForVisibleRows];
if ([arr containsObject:indexPath])
{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];//received error here
UIImageView *imageView = (UIImageView *)[cell viewWithTag:'ICON'];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
UIImage *image = [manager imageWithURL:downloader.url];
imageView.image = image;
}
}
This is a delegate of SDWebImageDownloader and received error when update:
thread9: Program received signal: "SIGABRT".
Form the device console, there is:
: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 7 beyond bounds [0 .. 6]'
*** First throw call stack:
(0x335a38bf 0x300971e5 0x334ecb6b 0x30ff0eb1 0xaa0a7 0x334fd435 0xb5b13 0x30d91a91 0x30e255a1 0x36fa0c1d 0x36fa0ad8)
Then I print the arr which holds the current visible index path:
Printing description of arr:
(
" 2 indexes [0, 1]",
" 2 indexes [0, 2]",
" 2 indexes [0, 3]",
" 2 indexes [0, 4]",
" 2 indexes [0, 5]",
" 2 indexes [0, 6]",
" 2 indexes [0, 7]"
)
and the received indexPath
2 indexes [0, 7]
The indexPath is included in the visible index path, and why it still cause the NSRangeException?
It looks like a bug for cellForRowAtIndexPath:indexPath, as the row of index path is 7 which is beyond the visible index path arr, am I right?
Add the eatableview delegate method:
- (UITableViewCell *)tableView:(UITableView *)inTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSString *path;
NSString *filename;
BOOL download = YES;
NSDictionary *tempDic = nil;
#synchronized (documentDirectoryFileList) {
tempDic = [self.documentDirectoryFileList objectAtIndex:indexPath.row];
filename = [tempDic objectForKey:#"filename" ];
NSURL *url = [tempDic objectForKey:#"url" ];
if ( url ) {
path = [ url path ];
download= [ self downloadedFile:url ];
} else {
path = [tempDic objectForKey:#"filepath" ];
}
}
BOOL isDirectory = FALSE;
NSFileManager *fileManager = [[NSFileManager alloc] init];
BOOL found = [fileManager fileExistsAtPath: path isDirectory: &isDirectory];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGRect rect;
rect = CGRectMake(5,14, 32, 32);
cell.userInteractionEnabled = YES;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
imageView.tag = 'ICON';
[cell.contentView addSubview:imageView];
[imageView release];
rect = CGRectMake(42, 10, 238, 22);
UILabel *labelView = [[UILabel alloc] initWithFrame:rect];
labelView.tag = 'NAME';
labelView.font = [UIFont boldSystemFontOfSize:18];
if ( download == NO )
labelView.textColor = [UIColor lightGrayColor ];
[cell.contentView addSubview:labelView];
[labelView release];
rect = CGRectMake(42, 34, 200, 20);
labelView = [[UILabel alloc] initWithFrame:rect];
labelView.tag = 'TIME';
labelView.font = [UIFont systemFontOfSize:12];
if ( download == NO )
labelView.textColor = [UIColor lightGrayColor ];
[cell.contentView addSubview:labelView];
[labelView release];
rect = CGRectMake(200, 34, 75, 20);
labelView = [[UILabel alloc] initWithFrame:rect];
labelView.tag = 'SIZE';
labelView.font = [UIFont systemFontOfSize:12];
if ( download == NO )
labelView.textColor = [UIColor lightGrayColor ];
labelView.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview:labelView];
[labelView release];
}
// Get the time zone wrapper for the row
UIImageView *imageView = (UIImageView *)[cell viewWithTag:'ICON'];
imageView.image = NULL;
NSString* extension = [[path pathExtension] lowercaseString];
if ([extension isEqualToString: #"png"] ||
[extension isEqualToString: #"jpg"] ||
[extension isEqualToString: #"jpeg"] ||
[extension isEqualToString: #"bmp"] ||
[extension isEqualToString: #"gif"] ||
[extension isEqualToString: #"tiff"] ||
[extension isEqualToString: #"thm"])
{
NSString *realFilePath = [ fileManager destinationOfSymbolicLinkAtPath:path error:nil ];
if ( realFilePath )
path = realFilePath;
NSURL *url = [[NSURL fileURLWithPath:path] URLByAppendingPathComponent:#"thumb.th"];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
UIImage *temp = [manager imageWithURL:url];
if (temp) {
imageView.image = temp;
}
else
{
SDWebImageDownloader *downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self indexPath:indexPath];
}
} else {
imageView.image = [ self determineFileIcon : path ];
}
// Configure the cell.
UILabel *labelView = (UILabel *)[cell viewWithTag:'NAME'];
labelView.text = filename;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
if ( isDirectory ) {
if ( isLink( path ) )
labelView.font = [UIFont italicSystemFontOfSize:16.0];
else
labelView.font = [UIFont boldSystemFontOfSize:16.0];
} else {
if ( isLink( path ) )
labelView.font = [UIFont italicSystemFontOfSize:16.0];
else
labelView.font = [UIFont systemFontOfSize:16.0];
}
labelView = (UILabel *)[cell viewWithTag:'TIME'];
NSCalendar *theCalendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [tempDic objectForKey:#"date" ];
NSDateComponents *dateComponents = [theCalendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[theCalendar release];
labelView.text = [NSString stringWithFormat:#"%d/%02d/%02d %02d:%02d:%02d", year,month,day,hour,minute,second ];
if ( !isDirectory ) {
labelView = (UILabel *)[cell viewWithTag:'SIZE'];
[labelView setHidden:NO];
NSNumber *size = [tempDic objectForKey:#"filesize" ];
float value = [ size floatValue ];
NSString *str;
if ( value > ( 1024*1024 ) ) {
value = value / 1024 / 1024;
str = [NSString stringWithFormat:#"%0.1f MB", value ];
} else if ( value > 1024 ) {
value = value / 1024;
str = [NSString stringWithFormat:#"%0.1f KB", value ];
} else {
str = [NSString stringWithFormat:#"%d Bytes", [ size integerValue ] ];
}
labelView.text = str;
}
else
{
labelView = (UILabel *)[cell viewWithTag:'SIZE'];
[labelView setHidden:YES];
}
[fileManager release];
return cell;
}
Added on 11-17:
when the "SIGABRT" receives, the documentDirectoryFileList has the objects, for example 30+. The received indexPath is existed in the visible index path array. But I noticed that: it is easy to happen when I scroll the tableview. There is no new object added to the datasource. what I do is just updating the image on the cell.
I guess it maybe:
when the received index path begin to update the corresponding cell, I happen to scroll it and the cell or the indexpath is no longer visible. And then it crashes.
It seems a kind of problem about multithread.
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithIndexPath:(NSIndexPath *)indexPath
{
#synchronized(tableView)
{
NSArray *arr = [self.tableView indexPathsForVisibleRows];
if ([arr containsObject:indexPath])
{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (!cell)
{
return;
}
UIImageView *imageView = (UIImageView *)[cell viewWithTag:'ICON'];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
UIImage *image = [manager imageWithURL:downloader.url];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = image;
});
}
}
}
}
or you can
- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithIndexPath:(NSIndexPath *)indexPath
{
#synchronized(tableView)
{
NSArray *arr = [self.tableView indexPathsForVisibleRows];
if ([arr containsObject:indexPath])
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
});//must be in main thread; reloadRowsAtIndexPaths: is not thread safe
}
}
}