Я создал Custom UITableViewCell с использованием файла XIB и заставил его работать в UITableView. Я разработал пользовательскую ячейку и ее подвиды в портретных размерах, но когда я поворачиваю устройство в ландшафтном режиме, я хочу изменить размер ячейки и ее подвидов. Я написал для этого следующий код, но не уверен, почему только одна ячейка в видимых ячейках изменяется, а остальные остаются прежними! Может ли кто-нибудь помочь мне со стандартной практикой изменения размера пользовательской ячейки и их подвидов? Спасибо.
#pragma mark - UITableView delegate methods
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomTableViewCellIdentifier";
CustomTableViewCell *cell = (CustomTableViewCell*)[tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// Load custom cell from NIB
self.customTableViewCell = [[[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil] objectAtIndex:0];
cell = _customTableViewCell;
}
// Use cell
...
}
#pragma mark - Layout views
- (void)layoutForOrientation:(UIInterfaceOrientation)orientation {
if (UIInterfaceOrientationIsPortrait(orientation))
[self layoutPortraitViews];
else
[self layoutLandscapViews];
}
- (void)layoutLandscapViews {
self.customTableViewCell.frame = CGRectMake(0, 0, 1024, 40);
self.customTableViewCell.contentSize = CGSizeMake(1024, 40);
self.customTableViewCell.cellBackgroundImageView.frame = CGRectMake(0, 0, 1024, 40);
self.customTableViewCell.assetNameLabel.frame = CGRectMake(15, 0, 245, 20);
self.customTableViewCell.assetTypeLabel.frame = CGRectMake(15, 20, 245, 20);
self.customTableViewCell.assetImageView.frame = CGRectMake(265, 20, 120, 20);
self.customTableViewCell.assetValueLabel.frame = CGRectMake(265, 20, 120, 20);
[self.tableView reloadData];
}
- (void)layoutPortraitViews {
self.customTableViewCell.frame = CGRectMake(0, 0, 768, 40);
self.customTableViewCell.contentSize = CGSizeMake(768, 40);
self.customTableViewCell.cellBackgroundImageView.frame = CGRectMake(0, 0, 768, 40);
self.customTableViewCell.assetNameLabel.frame = CGRectMake(15, 0, 180, 20);
self.customTableViewCell.assetTypeLabel.frame = CGRectMake(15, 20, 180, 20);
self.customTableViewCell.assetImageView.frame = CGRectMake(200, 20, 90, 20);
self.customTableViewCell.assetValueLabel.frame = CGRectMake(200, 20, 90, 20);
[self.tableView reloadData];
}
[РЕШЕНИЕ]
После небольшой борьбы это заработало. Изменение размера ячейки и ее подвидов не сработает, так как мне приходится обрабатывать изменения ориентации, продолжать повторно использовать ячейку для повышения производительности, а видимые ячейки меняются при повороте устройства, поэтому я не смог найти решение, используя мой первый подход. Вот мое другое решение.
Здесь задача состоит в том, чтобы обрабатывать ориентации и пользовательские ячейки вместе без ущерба для производительности.
Я создал два вида ячеек в NIB, один для портрета, а другой для ландшафта.
Используются две переменные;
BOOL refreshing;
UIInterfaceOrientation currentOrientation;
Из поля зрения появится;
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
[self layoutForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
От делегатов ротации;
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
refreshing = YES;
currentOrientation = toInterfaceOrientation;
[UIView animateWithDuration:duration animations:^{
[self.tableView reloadData];
[self layoutForOrientation:toInterfaceOrientation];
}];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
refreshing = NO;
}
От делегата tableview;
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomTableViewCellIdentifier";
CustomTableViewCell *cell = (CustomTableViewCell*)[tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil || refreshing)
{
if (UIInterfaceOrientationIsPortrait(currentOrientation))
cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil] objectAtIndex:0];
else
cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomTableViewCell" owner:self options:nil] objectAtIndex:1];
}
//Use cell
}
... поэтому это решение будет перезагружать ячейки только тогда, когда произойдет событие изменения ориентации. Удачного кодирования :-)