Popover не находится на кнопке
Я пытаюсь центрировать popover на кнопке. Кажется, я не могу понять, где я могу ошибиться. Вместо стрелки, находящейся в середине кнопки, она находится в центре на половину ширины экрана.
@IBAction func buttonClicked(sender: AnyObject){
var popoverViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ServiceOptions") as! ServiceOptionsPopover
popoverViewController.delegate = self
popoverViewController.modalPresentationStyle = .Popover
popoverViewController.preferredContentSize = CGSizeMake(300, 300)
let popoverPresentationViewController = popoverViewController.popoverPresentationController
popoverPresentationViewController?.permittedArrowDirections = .Up
popoverPresentationViewController?.delegate = self
popoverPresentationViewController?.sourceView = sender as! UIButton
popoverPresentationViewController?.sourceRect = sender.frame
presentViewController(popoverViewController, animated: true, completion: nil)
}
Ответы
Ответ 1
Проблема заключается в элементарном запутанном фрейме и границах:
popoverPresentationViewController?.sourceView = sender as! UIButton
popoverPresentationViewController?.sourceRect = sender.frame
Нет! Вы имеете в виду границы:
popoverPresentationViewController?.sourceView = sender as! UIButton
popoverPresentationViewController?.sourceRect = (sender as! UIButton).bounds
Причина в том, что sourceRect
задан в координатном пространстве sourceView
- то есть, если вы хотите, чтобы он был прямым, это границы этого представления.
Ответ 2
В iOS есть проблема. Установка привязки в раскадровке:
![введите описание изображения здесь]()
... приводит к тому, что стрелка не центрируется на якоре:
![введите описание изображения здесь]()
Чтобы решить проблему, добавьте ее в prepareForSegue:sender:
:
// Fixes popover anchor centering issue in iOS 9
if let popoverPresentationController = segue.destinationViewController.popoverPresentationController, sourceView = sender as? UIView {
popoverPresentationController.sourceRect = sourceView.bounds
}
![введите описание изображения здесь]()
Ответ 3
Вот правильный способ:
@IBAction func buttonClicked(sender: UIButton){
var popoverViewController = UIViewController()
popoverViewController.view.frame = CGRectMake(0,0, 300, 300)
popoverViewController.view.backgroundColor = UIColor.redColor()
popoverViewController.modalPresentationStyle = .Popover
popoverViewController.preferredContentSize = CGSizeMake(300, 300)
let popoverPresentationViewController = popoverViewController.popoverPresentationController
popoverPresentationViewController?.permittedArrowDirections = .Up
popoverPresentationViewController?.sourceView = sender
popoverPresentationViewController?.sourceRect = CGRectMake(0, 0, sender.bounds.width,sender.bounds.height) // see this line of code
presentViewController(popoverViewController, animated: true, completion: nil)
}
Ответ 4
В моем случае проблема отличается, popover показан для UIBarButtonItem с пользовательским представлением. Для iOS 11, если вы используете пользовательский вид UIBarButtonItem, пользовательское представление должно быть удобным для компоновки.
С помощью этой категории вы можете быстро применить ограничения.
UIView + NavigationBar.h
@interface UIView (NavigationBar)
- (void)applyNavigationBarConstraints:(CGFloat)width height:(CGFloat)height;
- (void)applyNavigationBarConstraintsWithCurrentSize;
@end
UIView + NavigationBar.m
#import "UIView+NavigationBar.h"
@implementation UIView (NavigationBar)
- (void)applyNavigationBarConstraints:(CGFloat)width height:(CGFloat)height
{
if (width == 0 || height == 0) {
return;
}
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:height];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:width];
[heightConstraint setActive:TRUE];
[widthConstraint setActive:TRUE];
}
- (void)applyNavigationBarConstraintsWithCurrentSize {
[self applyNavigationBarConstraints:self.bounds.size.width height:self.bounds.size.height];
}
@end
Затем вы можете сделать:
UIButton *buttonMenu = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonMenu setImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
buttonMenu.frame = CGRectMake(0, 0, 44, 44);
[buttonMenu addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
//Apply constraints
[buttonMenu applyNavigationBarConstraintsWithCurrentSize];
UIBarButtonItem *menuBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonMenu];
Когда вы применяете ограничения, пометка отображается корректно на пользовательском представлении, например, код для показа оповещения в виде popover:
UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Menu" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
//Add actions ....
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.sourceView = buttonMenu;
popController.sourceRect = buttonMenu.bounds;
[self presentViewController:controller animated:YES completion:nil];