sho*_*shi 18 uibarbuttonitem uipopovercontroller ios
我在一个项目中注意到,由于某种原因,右侧栏按钮项目上的弹出框的位置似乎偏向右侧.我尝试使用UIButton作为自定义视图,然后从该按钮呈现弹出窗口,但是如果我实际上为它提供了'居中'值,则popover似乎忽略了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];
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我切换到使用内部按钮,如上所述,我看到类似的行为(注意颜色变化,因此图像显示).

这个代码仍然相当简单:
- (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];
}
Run Code Online (Sandbox Code Playgroud)
请注意,我没有使用实际的中心,而是使用了任意值,2.如果我使用1或0,则弹出框将变为左对齐.任何大于1的东西都会再次右对齐.

我搜索了一下类似的问题,但我似乎找不到任何有同样问题的人.任何关于导致这种情况或如何避免它的想法将不胜感激.我唯一能够猜到的是,由于它靠近边缘,Apple做了一些定位巫术,迫使它成为他们想要的地方.问题是右上角按钮看起来像一个非常标准的下拉位置.
编辑:我已经确认,长按本机邮件应用程序中的"新邮件"图标会发生同样的行为.
编辑2:我能够向Apple确认这是一个问题.在最近的一个版本中(我记不起哪个版本,我认为是9个版本中的一个版本),他们制作了它,因此你可以手动设置它.默认行为仍然是错误的我相信(我有一段时间没试过),但你可以使用CGRect偏移方法使其正常工作,如果你这么倾向.
这是执行此操作的一种方法:不使用 a UIBarButtonSystemItem,而是将 aUIBarButtonItem与自定义视图一起使用。只需将 a 拖入UIButton即可UINavigationBar获得UIBarButtonItem嵌入了 的a UIButton,它显示为 的UIBarButtonItemcustomView。
@IBAction func didTapActionButton(_ sender: Any) {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "myPopover") {
vc.modalPresentationStyle = .popover
guard let innerView = actionButton.customView else {
// Unexpected missing custom view
return
}
vc.popoverPresentationController?.sourceView = navigationController?.navigationBar
vc.popoverPresentationController?.sourceRect = innerView.frame
self.present(vc, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)