在我的情况下,问题是不同的,弹出窗口显示的是一个带有自定义视图的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];
[buttonMenu applyNavigationBarConstraintsWithCurrentSize];
UIBarButtonItem *menuBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonMenu];
一旦您应用了约束条件,弹出窗口将正确显示在自定义视图上,例如,显示警报作为弹出窗口的代码如下:
UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Menu" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.sourceView = buttonMenu;
popController.sourceRect = buttonMenu.bounds;
[self presentViewController:controller animated:YES completion:nil];