2014-01-27 2 views
1

Я использую библиотеку SDWebImage для загрузки изображений для UIImageView в UITableView. Содержание моего Tableview массив инициализируется в viewDidLoad, как показано ниже:Добавление UIImageView в UITableview условно с использованием SDWebImage

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
self.myArray [email protected][@"http://i.imgur.com/CUwy8ME.jpg",@"http://i.imgur.com/lQRlubz.jpg",@"AlAhmed",@"Welcome",@"jfhskjh",@"hfyyu",@"lkdjfs",@"mfjsoi",@"jsdkjhdksjh",@"ljsdkfhuhs"]; 

[self.tableView setRowHeight:100]; 

[self.tableView reloadData]; 

} 

Моя идея заключается в том, чтобы обнаружить, если URL существует в туАггау и, следовательно, для загрузки изображения в этой ячейке. Мой код работает нормально, но изображения отображаются в других ячейках (я думаю, что повторно использую ячейки), но я не мог решить проблему.

А вот код для Tableview делегата

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Celll"; 
UITableViewCell *cell = (UITableViewCell *)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier]; 

UIImageView *imgView=nil; 
if(cell == nil) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)]; 
    [cell.contentView addSubview:imgView]; 
} 


NSError *error; 
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error]; 

NSString *myString = [self.myArray objectAtIndex:indexPath.row]; 
NSArray *matches = [detector matchesInString:myString 
            options:0 
             range:NSMakeRange(0, [myString length])]; 

for (NSTextCheckingResult *match in matches) { 
    if ([match resultType] == NSTextCheckingTypeLink) { 
     NSURL *url = [match URL]; 

     [imgView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"120.png"] completed:^(UIImage *image,NSError *error, SDImageCacheType cacheType){ 
     }]; 
    } 

} 


[ cell.textLabel setText:[self.myArray objectAtIndex:indexPath.row]]; 


return cell; 
} 

Пожалуйста, мне нужна ваша большая помощь.

+0

Как вы уже отметили @Putz, вы должны использовать собственный класс TableCell, но добавление subView UIImageView в contentView камеры и извлечение с помощью тега сделают трюк. – chandu

ответ

0

Возможно, вам придется подклассифицировать UITableViewCell и добавить imgView в качестве переменной класса. Затем в вашем dequeueReusableCellWithIdentifier вы можете проверить возвращенную ячейку, чтобы узнать, существует ли уже imgView. Затем вы можете обновить или удалить imgView на основе ваших проверок.

Поскольку у вас есть это сейчас, вы добавляете изображение в содержимое contentView. Затем эта ячейка повторно используется (все еще содержит старый образ), и вы добавляете еще один образ. Вскоре это будет кошмар памяти.

EDIT: Теперь с кодом! (И 33% меньше жира!)

@interface CustomCell : UITableViewCell 

@property (nonatomic, strong) UIImageView *imageView; 

@end 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Celll"; 
UITableViewCell *cell = (UITableViewCell *)[tableView  dequeueReusableCellWithIdentifier:CellIdentifier]; 

UIImageView *imgView=nil; 
if(cell == nil) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

if(cell.imageView) 
{ 
    cell.imageView.image = nil; 
} 
else 
{ 
    cell.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)]; 
    [cell.contentView addSubview:cell.imageView]; 
} 


NSError *error; 
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error]; 

NSString *myString = [self.myArray objectAtIndex:indexPath.row]; 
NSArray *matches = [detector matchesInString:myString 
            options:0 
             range:NSMakeRange(0, [myString length])]; 

for (NSTextCheckingResult *match in matches) { 
    if ([match resultType] == NSTextCheckingTypeLink) { 
     NSURL *url = [match URL]; 

     [cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"120.png"] completed:^(UIImage *image,NSError *error, SDImageCacheType cacheType){ 
     }]; 
    } 

} 


[ cell.textLabel setText:[self.myArray objectAtIndex:indexPath.row]]; 


return cell; 
} 

Таким образом, вы удалите файл, если он уже загружен в ячейку, то беспокоиться о перегрузке это так же, как вы сейчас находитесь. Это делает так, что если вы когда-либо захотите обновить изображение, у вас будет легкий доступ к нему для внесения изменений.

+0

Спасибо за вашу помощь, не могли бы вы показать мне пример кода для вашего решения? – user1887971

+0

@ user1887971 обновлен с небольшим количеством кода. Вы должны быть в состоянии взять это оттуда. – Putz1103

0

Спасибо, ребята, за ваши предложения. Я создал подкласс UITableViewCell под названием CustomClass.h/.m, и я создал CusstomCell.xib, а затем добавил объект UITableViewCell в файл nib с добавлением UIImageView в ячейку.

@property (weak, nonatomic) IBOutlet UIImageView *myImageView; 

Затем я отредактировал свой код следующим образом, и он отлично работает.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath 
{ 
static NSString *customCellIdentifier = @"MyCell"; 
CustomCell *myCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:customCellIdentifier]; 
if (myCell == nil) { 
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CustomCell" owner:self options:nil]; 
    myCell = [nib lastObject]; 
} 

    NSURL *url =[self LookForURLinString:[self.myArray objectAtIndex:indexPath.row]]; 
if (url) { 
    [myCell.myImageView setImageWithURL:url 
         placeholderImage:[UIImage imageNamed:@"120.png"] 
           completed:^(UIImage *image,NSError *error, SDImageCacheType cacheType){}]; 
} 
else { 
    [myCell.myImageView setImage:nil]; 
    [myCell.myImageView removeFromSuperview]; 
} 
[myCell.textLabel setText:[self.myArray objectAtIndex:indexPath.row]]; 
return myCell; 


} 
-(NSURL *)LookForURLinString:(NSString *)string 
{ 
NSError *error; 
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error]; 



NSArray *matches = [detector matchesInString:string 
            options:0 
             range:NSMakeRange(0, [string length])]; 

for (NSTextCheckingResult *match in matches) { 
    if ([match resultType] == NSTextCheckingTypeLink) { 
     NSURL *url = [match URL]; 
     return url; 
    } 
} 
return nil; 

}