2013-10-08 2 views
1

Я добавляю изображения в свой вид ячейки из plist. Также у меня такая же проблема с изображениями, которые я сохраняю на plist, используя URL-адрес. Они разных размеров. Я бы хотел изменить их до определенного размера, чтобы они все выглядели одинаково. Я попытался использовать:установка размера изображения, добавленного в ячейку в виде таблицы

cell.imageView.contentMode = UIViewContentModeScaleAspectFill; 
cell.imageView.clipsToBounds = YES; 

Это не сработало. Я пробовал кучу других вещей и не добился успеха. Я искал кучу вещей и не нашел ничего полезного. Вот моя ячейка для метода ряда:

- (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]; 
    } 

    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     cell.textLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:@"city"]; 
     cell.detailTextLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:@"state"]; 
     cell.imageView.image = [UIImage imageNamed:[[self.searchResults objectAtIndex:indexPath.row] valueForKey:@"cityImage"]]; 
     cell.imageView.contentMode = UIViewContentModeScaleAspectFill; 
     cell.imageView.clipsToBounds = YES; 
    } else { 
     cell.textLabel.text = [[content objectAtIndex:indexPath.row] valueForKey:@"city"]; 
     cell.detailTextLabel.text = [[content objectAtIndex:indexPath.row] valueForKey:@"state"]; 
     // Construct the expected URL for the image. 
     NSURL *imageFileURL = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0]; 
     imageFileURL = [imageFileURL URLByAppendingPathComponent:[[self.content objectAtIndex:indexPath.row] valueForKey:@"cityImage"] isDirectory:NO]; 
     // Attempt to load the image at the above URL. 
     cell.imageView.image = [[UIImage alloc] initWithContentsOfFile:[imageFileURL path]]; 
     if (!cell.imageView.image) 
      cell.imageView.image = [UIImage imageNamed:[[self.content objectAtIndex:indexPath.row] valueForKey:@"cityImage"]]; 
     cell.imageView.contentMode = UIViewContentModeScaleAspectFill; 
     cell.imageView.clipsToBounds = YES; 
    } 

    return cell; 
} 

Для жизни меня я не могу понять это. Я знаю, что это может быть легко исправить, но я не могу думать ни о чем другом.

Edit:

Как было предложено, я создал пользовательскую ячейку, объявил layoutSubviews там и затем подклассы ячейки следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 
    MyCostumCell *cell = (MyCostumCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[MyCostumCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier]; 
    } 

    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     cell.textLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:@"city"]; 
     cell.detailTextLabel.text = [[searchResults objectAtIndex:indexPath.row] valueForKey:@"state"]; 
     cell.imageView.image = [UIImage imageNamed:[[self.searchResults objectAtIndex:indexPath.row] valueForKey:@"cityImage"]]; 
     //cell.textLabel.textColor = [UIColor colorWithRed:153.0/255.0f green:0.0/255.0f blue:0.0/255.0f alpha:1]; 
    } else { 

     cell.textLabel.text = [[content objectAtIndex:indexPath.row] valueForKey:@"city"]; 
     cell.detailTextLabel.text = [[content objectAtIndex:indexPath.row] valueForKey:@"state"]; 
     // Construct the expected URL for the image. 
     NSURL *imageFileURL = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0]; 
     imageFileURL = [imageFileURL URLByAppendingPathComponent:[[self.content objectAtIndex:indexPath.row] valueForKey:@"cityImage"] isDirectory:NO]; 
     // Attempt to load the image at the above URL. 
     cell.imageView.image = [[UIImage alloc] initWithContentsOfFile:[imageFileURL path]]; 
     if (!cell.imageView.image) 
      cell.imageView.image = [UIImage imageNamed:[[self.content objectAtIndex:indexPath.row] valueForKey:@"cityImage"]]; 
    } 

    return cell; 
} 

Опять же, это не сработало. Вот снимок экрана:

enter image description here

+0

вы обязательно должны сделать некоторое чтение документального фильма. ваша формулировка полностью смущена. В 'cellForRowAtIndexPath:' вы не подклассифицируете ячейку. u используйте подклассу. – vikingosegundo

ответ

7

вы подкласс UITableViewCell. но вы не должны создать совершенно новый вид, как иерархию предложил Данте, но перезаписать -layoutSubviews

@interface VideoItemCell : UITableViewCell 
@end 


@implementation VideoItemCell 
-(void)layoutSubviews 
{ 
    [super layoutSubviews]; 
    self.imageView.contentMode = UIViewContentModeScaleAspectFill; 
    self.imageView.frame = CGRectMake(self.imageView.frame.origin.x, self.imageView.frame.origin.y, 100, 100); 
} 

@end 

В контроллере Tableview

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    VideoItemCell *cell = (VideoItemCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[VideoItemCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier]; 
    } 

    //… 
    return cell; 
} 
+0

Я попытался добавить метод, и я получаю ошибку, не вижу видимого @interface для uitableview, объявляет селектор layoutsubview. –

+0

вам нужно подклассифицировать ячейку, а не вид таблицы – vikingosegundo

+0

, как бы я сделал это, учитывая код, который у меня выше? –

1

По умолчанию TableViewCell изменяет размер ImageView в зависимости от размера изображения. Для решения этой проблемы можно использовать пользовательский элемент, имеющий собственное изображение вид ..

Более подробную информацию о том, как создать пользовательские ячейки

How do you load custom UITableViewCells from Xib files?

+0

спасибо за ссылку, но она слишком старая и не работает. также я попробовал пользовательскую ячейку, создающую изображение, через представление изображения и назначил ему теги. это тоже не сработало. что-нибудь еще, что вы можете предложить? –

+0

ответ по-прежнему работает .. вы можете попытаться сделать правильный шаг в Google, чтобы помочь вам сделать это правильно. – Shubhank

Смежные вопросы