Как правильно представить popover из UITableViewCell с помощью UIPopoverArrowDirectionRight или UIPopoverArrowDirectionLeft
Я всегда пытаюсь представить popover из ячейки внутри tableView таким образом:
[myPopover presentPopoverFromRect:cell.frame inView:self.tableView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
но я не могу использовать UIPopoverArrowDirectionRight или Left, потому что, в зависимости от позиции
ipad (портрет или пейзаж), popover появляется где-то еще.
Я представляю popover правильный путь?
PS: представление таблицы находится в подробном представлении splitView.
Ответы
Ответ 1
Вот простое решение, которое отлично работает для меня
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
CGRect rect=CGRectMake(cell.bounds.origin.x+600, cell.bounds.origin.y+10, 50, 30);
[popOverController presentPopoverFromRect:rect inView:cell permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
Ответ 2
Вы получаете кадр из ячейки через метод rectForRowAtIndexPath. Это верно. Однако tableview, скорее всего, является подвидю большего видения iPad, поэтому, когда popover получает координаты, они думают, что они находятся в увеличенном виде. Вот почему popover появляется не в том месте.
Пример: CGRect для строки (0,40,320,44). Вместо того, чтобы popover таргетинг на этот кадр в представлении таблицы, он вместо этого нацеливается на этот кадр на вашем основном представлении.
Я решил эту проблему, преобразовывая кадр из относительных координат таблицы в координаты в моем увеличенном виде.
код:
CGRect aFrame = [self.myDetailViewController.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:theRow inSection:1]];
[popoverController presentPopoverFromRect:[self.myDetailViewController.tableView convertRect:aFrame toView:self.view] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
Надеюсь, что это поможет другим, кто ищет эту проблему.
Ответ 3
Сегодня я столкнулся с этой проблемой, и я нашел более простое решение.
При создании экземпляра popover вам нужно указать представление содержимого ячейки:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIViewController *aViewController = [[UIViewController alloc] init];
// initialize view here
UIPopoverController *popoverController = [[UIPopoverController alloc]
initWithContentViewController:aViewController];
popoverController.popoverContentSize = CGSizeMake(320, 416);
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[popoverController presentPopoverFromRect:cell.bounds inView:cell.contentView
permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
[aView release];
// release popover in 'popoverControllerDidDismissPopover:' method
}
Ответ 4
В Swift между приведенными выше ответами это работает для меня на iPad в любой ориентации:
if let popOverPresentationController : UIPopoverPresentationController = myAlertController.popoverPresentationController {
let cellRect = tableView.rectForRowAtIndexPath(indexPath)
popOverPresentationController.sourceView = tableView
popOverPresentationController.sourceRect = cellRect
popOverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Any
}
Ответ 5
Я тоже столкнулся с этой проблемой. Решением для меня было просто изменить ширину прямоугольника, возвращаемого CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath
:
CGRect rect = [aTableView rectForRowAtIndexPath:indexPath];
//create a 10 pixel width rect at the center of the cell
rect.origin.x = (rect.size.width - 10.0) / 2.0;
rect.size.width = 10.0;
[self.addExpensePopoverController presentPopoverFromRect:rect inView:aTableView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Создайте прямоугольник внутри ячейки. Таким образом, у popover больше шансов найти хорошее место для позиционирования.
Ответ 6
Чтобы поместить popover рядом с игрой, вы можете использовать этот код:)
Я использую это для более расширенного использования :
- находит пользовательский метод accesoryView (cell.accesoryView)
- если пусто, найдите сгенерированный accesoryView (UIButton), если ячейка имеет
- Если UIButton не существует, найдите представление соты (UITableViewCellContentView)
- Если вид сокета ячейки не существует, используйте представление ячейки
Может использоваться для UIActionSheet или UIPopoverController.
Вот мой код:
UIView *accessoryView = cell.accessoryView; // finds custom accesoryView (cell.accesoryView)
if (accessoryView == nil) {
UIView *cellContentView = nil;
for (UIView *accView in [cell subviews]) {
if ([accView isKindOfClass:[UIButton class]]) {
accessoryView = accView; // find generated accesoryView (UIButton)
break;
} else if ([accView isKindOfClass:NSClassFromString(@"UITableViewCellContentView")]) {
// find generated UITableViewCellContentView
cellContentView = accView;
}
}
// if the UIButton doesn't exists, find cell contet view (UITableViewCellContentView)
if (accessoryView == nil) {
accessoryView = cellContentView;
}
// if the cell contet view doesn't exists, use cell view
if (accessoryView == nil) {
accessoryView = cell;
}
}
[actionSheet showFromRect:accessoryView.bounds inView:accessoryView animated:YES];
Протестировано в iOS 4.3 до 5.1
Лучше всего использовать в качестве настраиваемого метода:
-(UIView*)getViewForSheetAndPopUp:(UITableViewCell*)cell;
И код метода:
-(UIView*)getViewForSheetAndPopUp:(UITableViewCell*)cell {
UIView *accessoryView = cell.accessoryView;
if (accessoryView == nil) {
UIView *cellContentView = nil;
for (UIView *accView in [cell subviews]) {
if ([accView isKindOfClass:[UIButton class]]) {
accessoryView = accView;
break;
} else if ([accView isKindOfClass:NSClassFromString(@"UITableViewCellContentView")]) {
cellContentView = accView;
}
}
if (accessoryView == nil) {
accessoryView = cellContentView;
}
if (accessoryView == nil) {
accessoryView = cell;
}
}
return accessoryView;
}
Ответ 7
Кадр ячейки будет примерно 0,0, ширина, размер, я не верю, что он будет иметь X и Y относительно таблицыView... вы хотите использовать - (CGRect) rectForRowAtIndexPath: (NSIndexPath * ) indexPath для этого, это должно вернуть вам правильный фрейм для ячейки относительно tableView... вот ссылка UITAbleView ref
Ответ 8
У меня была такая же проблема, вот обходной путь, который я использовал:
- в моем UITableViewCell, я добавил Actions (IBActions как я создаю свои ячейки из NIB) для кнопок сотовой ячейки.
- Затем я определил протокол CellActionDelegate, который имитирует мои селекторы действий, к которым у меня была моя кнопка (отправитель) и моя ячейка (self)
- тогда detailViewController моего splitViewController реализует этот протокол, преобразовывая его из ячейки в его координаты...
здесь пример кода
В MyCustomTableViewCell.m:
-(IBAction)displaySomeCellRelativePopover:(id)sender{
//passes the actions to its delegate
UIButton *button = (UIButton *)sender;
[cellActionDelegate displaySomeCellRelativePopoverWithInformation:self.info
fromButton:button
fromCell:self];
}
и в MyDetailViewController.m:
-(void)displaySomeCellRelativePopoverWithInformation:(MyCellInformationClass *)info
fromButton:(UIButton *)button
fromCell:(UIView *)cell{
UIPopoverController * popoverController = nil;
//create your own UIPopoverController the way you want
//Convert your button/view frame
CGRect buttonFrameInDetailView = [self.view convertRect:button.frame fromView:cell];
//present the popoverController
[popoverController presentPopoverFromRect:buttonFrameInDetailView
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];]
//release objects created...
}
PS: Конечно, "действие" не обязательно должно быть IBAction, а кадр, из которого начинается popover, не обязательно должен быть UIButton - один UIView был бы хорошим:)
Ответ 9
Вот как я это сделал и прекрасно работает.
RidersVC *vc = [RidersVC ridersVC];
vc.modalPresentationStyle = UIModalPresentationPopover;
vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
UIPopoverPresentationController *popPresenter = [vc popoverPresentationController];
popPresenter.sourceView = vc.view;
popPresenter.barButtonItem= [[UIBarButtonItem alloc] initWithCustomView:button];
popPresenter.backgroundColor = [UIColor colorWithRed:220.0f/255.0f green:227.0f/255.0f blue:237.0f/255.0f alpha:1.0];
[self.parentVC presentViewController:vc animated:YES completion:NULL];
Ответ 10
Это также помогло мне:
//Which are the ABSOLUTE coordinates in from the current selected cell
CGRect frame =[self.view convertRect:[tbvEventsMatch rectForRowAtIndexPath:indexPath] fromView:tbvEventsMatch.viewForBaselineLayout];