2015-11-18 4 views
1

У меня есть таблица элементов (UITableViewController), где я представляю элементы с помощью настраиваемых ячеек. Слева от каждой ячейки у меня есть уменьшенное изображение, и когда вы нажимаете на него (на кнопке над изображением, если быть точным), появляется всплывающее окно, которое должно показывать увеличенное изображение. Оно хорошо работает только для первой ячейки :UIPopoverPresentationController неуместен

Image popover looks good for the first row

Щелкнув на клетках, которые ниже показаны ошибочно сдвинуты поповер и неполучение увеличивается, когда вы идете от верхней части к нижней части таблицы:

Image popover looks misplaced for other rows

Я Наладка блок каждой ячейки внутри UITableViewController:

- (UITableViewCell *)tableView:(UITableView *)tableView 
    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Get a new or recycled cell 
BNRItemCell *cell = 
    [tableView dequeueReusableCellWithIdentifier:@"BNRItemCell" 
           forIndexPath:indexPath]; 

// Set the text on the cell with the description of the item 
// that is the nth index of items, where n = row this cell 
// will appear in on the tableview 
NSArray *items = [[BNRItemStore sharedStore] allItems]; 
BNRItem *item = items[indexPath.row]; 

// Configure the cell with the BNRItem 
cell.nameLabel.text = item.itemName; 
cell.serialNumberLabel.text = item.serialNumber; 
cell.valueLabel.text = [NSString stringWithFormat:@"$%d", item.valueInDollars]; 

cell.thumbnailView.image = item.thumbnail; 

cell.actionBlock = ^{ 
    NSLog(@"Going to show image for %@", item); 

    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){ 
     NSString *itemKey = item.itemKey; 

     // if there is no image, we don't need to display anything 
     UIImage *img = [[BNRImageStore sharedStore] imageForKey:itemKey]; 
     if (!img) { 
      return; 
     } 

     BNRImageViewController *ivc = [[BNRImageViewController alloc] init]; 
     ivc.image = img; 

     ivc.modalPresentationStyle = UIModalPresentationPopover; 
     ivc.preferredContentSize = CGSizeMake(380, 300); 
     CGRect frame = [self.view convertRect:cell.thumbnailView.bounds 
            fromView:cell.thumbnailView]; 
     // frame.origin.y -= 150; 

     UIPopoverPresentationController *popoverController = ivc.popoverPresentationController; 
     popoverController.permittedArrowDirections = UIPopoverArrowDirectionUp; 
     popoverController.sourceView = cell.thumbnailView; 
     popoverController.sourceRect = frame; 

     [self.navigationController presentViewController:ivc animated:YES completion:nil]; 


    } 
}; 

return cell; 

}

Блок выполняется при нажатии на кнопку зрения настраиваемым UITableViewCell:

@implementation BNRItemCell 

- (IBAction)showImage:(id)sender 
{ 
if (self.actionBlock) { 
    self.actionBlock(); 
} 
} 

@end 

actionBlock является property из BNRItemCell

Любая помощь будет принята с благодарностью ,

+0

Вы используете переменную «cell», но я не вижу способа, которым вы ее пытаетесь получить. Не могли бы вы поделиться тем, в каком методе вы находитесь? – Gordonium

+0

На самом деле, глядя на это - вы пытались заменить 'cell.thumbnailView.bounds' на' cell.thumbnailView.frame'? – Gordonium

+0

Это блок, который я устанавливаю в 'UITableViewController' (который отвечает за рисование таблицы). S 'method' tableView: cellForRowAtIndexPath: '. Затем блок настраивается как «свойство @» другого «UITableViewCell» (это настраиваемая ячейка), который выполняет блок при нажатии кнопки. –

ответ

4

Try что-то вроде:

CGRect frame = [cell.view convertRect:cell.thumbnailView.frame toView:self.view];

Хитрость здесь разница между bounds и frame. В случае кнопки его рамка находится там, где вы смотрите на ее супервизор (например, 42,42). Но в границах находится кнопка, соответствующая самой себе и ее собственным координатам (0,0).

Не смейтесь мой рисунок (я не дизайнер), но это может помочь:

enter image description here

Вы спрашиваете кнопку (или в случае UIImage) «, где вы относительно супервизора "(который в этом случае в основном представляет собой весь экран). Вы делаете это с помощью convertRect: toView:. Вы конвертируете фрейм эскиза (а не его границы) туда, где его координаты отображаются в виде супервизора.

+0

Не могли бы вы кратко прокомментировать, что было моей ошибкой и почему ваше предложение действительно устраняет проблему? –

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