我注意到在一个项目中,弹出窗口的定位在右侧按钮上似乎有些偏右。我尝试使用一个UIButton作为自定义视图代替,然后从该按钮呈现弹出窗口,但是如果我实际提供了“居中”值,弹出窗口似乎会忽略showFromRect。
这背后的代码非常简单:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareTap:)];
self.navigationItem.rightBarButtonItem = button;
}
- (void)shareTap:(UIBarButtonItem *)button {
self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];
[self.popover presentPopoverFromBarButtonItem:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
现在,如果我切换到使用内部按钮,如上所述,我会看到类似的行为(请注意颜色变化,以便图像显示出来)。
这段代码仍然相当简单:
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *innerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
[innerButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
[innerButton addTarget:self action:@selector(shareTap:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:innerButton];;
}
- (void)shareTap:(UIButton *)button {
self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];
// CGRect bottomCenter = CGRectMake(button.frame.size.width / 2, button.frame.size.height, 1, 1);
CGRect bottomCenter = CGRectMake(2, button.frame.size.height, 1, 1);
[self.popover presentPopoverFromRect:bottomCenter inView:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
注意,这里我使用了任意值2代替实际的中心点。如果我使用1或0,弹出框将左对齐,而大于1的任何值都将再次右对齐。
我搜索了一下类似的问题,但似乎没有找到有相同问题的人。任何关于导致这种情况的想法或如何避免它的建议都将不胜感激。我唯一能猜测的就是由于靠近边缘,Apple进行了某些定位操作以强制它呈现他们想要的效果。问题在于右上角的按钮看起来像一个相当标准的下拉位置。
编辑:我确认,在本机邮件应用程序中长按“新消息”图标会出现相同的行为。
编辑2:我已经向苹果确认了这个问题。在最近的某个版本中(我记不得是哪一个了,我想是9之一),他们使您可以手动设置此项。我认为默认行为仍然有问题(我已经有一段时间没有尝试过),但是您可以使用CGRect offset方法使其正常工作,如果您有兴趣的话。