如何在iPhone应用程序中创建弹出窗口?

15

我正在寻找iPhone中的气泡弹出窗口,并希望将其制作成类似于iOS 5阅读器功能的样式:

进入图片描述

经过一些研究,我发现了WEPopover和FPPopover,但我想知道是否有类似于此API内置于iPhone SDK中。


Swift答案 - Suragch
2个回答

26

你可以用一些自定义的艺术品制作一个UIView,并通过动画在你的视图上方显示它作为一个带有按钮的“弹出窗口”,就像这样:

UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(25, 25, 100, 50)]; //<- change to where you want it to show.

//Set the customView properties
customView.alpha = 0.0;
customView.layer.cornerRadius = 5;
customView.layer.borderWidth = 1.5f;
customView.layer.masksToBounds = YES;

//Add the customView to the current view
[self.view addSubview:customView];

//Display the customView with animation
[UIView animateWithDuration:0.4 animations:^{
    [customView setAlpha:1.0];
} completion:^(BOOL finished) {}];

如果你想使用customView.layer,请不要忘记导入#import <QuartzCore/QuartzCore.h>


如果我想在其中添加按钮,问题是所有的按钮都停留在一个位置,你有什么想法可以让我把按钮并排放置吗? - Xtrician
1
[yourButton setFrame:CGRectMake(5 /X/, 2 /Y/, 10 /Width/, 20 /Hight/)]; // 更改 X(5)和 Y(2)以进行定位 - Aleksander Azizi
8
请问您需要将以下内容翻译成中文:@AleksanderAzizi: where is the code that makes the triangle shape at the top left of the 'popover' view that you created? - BigSauce
我创建了一个带有按钮的自定义视图,当我点击按钮时,应该关闭自定义视图并显示前一个视图控制器。 - chandru

16
自从iOS8以后,我们现在能够创建弹出窗口,在iPhone和iPad上都是一样的,这对于那些制作通用应用程序的人来说非常棒,因此无需制作单独的视图或代码。
您可以在此处获取类以及演示项目: https://github.com/soberman/ARSPopover 您只需要继承UIViewController,遵循UIPopoverPresentationControllerDelegate协议并设置所需的modalPresentationStyle以及delegate值即可。
// This is your CustomPopoverController.m

@interface CustomPopoverController () <UIPopoverPresentationControllerDelegate>

@end

@implementation CustomPopoverController.m

- (instancetype)init {
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationPopover;
        self.popoverPresentationController.delegate = self;
    }
    return self;
}

- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone; //You have to specify this particular value in order to make it work on iPhone.
}

接下来,在您想要显示它的方法中实例化您新创建的子类,并将两个更多的值分配给sourceViewsourceRect。看起来像这样:

之后,在您希望展示它的方法中实例化您新创建的子类,并且给sourceViewsourceRect分配两个更多的值。它看起来像这样:

CustomPopoverController *popoverController = [[CustomPopoverController alloc] init];
popoverController.popoverPresentationController.sourceView = sourceView; //The view containing the anchor rectangle for the popover.
popoverController.popoverPresentationController.sourceRect = CGRectMake(384, 40, 0, 0); //The rectangle in the specified view in which to anchor the popover.
[self presentViewController:popoverController animated:YES completion:nil];

就是这样,一个漂亮、整洁而模糊的弹出框。


一条注释:self.modalPresentationStyle = UIModalPresentationPopover; 应该放在前面,否则 popoverPresentationController 将为空。 - Vitalii Gozhenko
1
太棒了。自从最初的问题以来,API已经发展了,现在这应该是被接受的答案。 - Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接