iOS實現Popover彈窗(類似氣泡彈窗)

前言

最近項目有一個需求需要實現一個類似氣泡的popover彈窗,就是點擊一個按鈕的時候在按鈕的某一個方向彈出一個視圖,這個視圖需要帶有一個箭頭指向。就像下圖是簡書和微信的樣式

簡書 系統樣式
微信 自定義樣式
系統樣式UIPopoverPresentationController

系統樣式就比較簡單了,就是一個UIViewController然后設置modalPresentationStyle屬性,要記住實現UIPopoverPresentationControllerDelegate代理的adaptivePresentationStyleForPresentationController方法
具體看代碼

- (IBAction)clickpopoverBtn:(id)sender {
    PopViewController *testVC = [[PopViewController alloc] init];
    testVC.preferredContentSize = CGSizeMake(150, 150);
    testVC.modalPresentationStyle = UIModalPresentationPopover;
    testVC.popoverPresentationController.delegate = self;
    testVC.popoverPresentationController.sourceView = self.popoverBtn;
    testVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    testVC.popoverPresentationController.backgroundColor = [UIColor redColor];
    testVC.popoverPresentationController.canOverlapSourceViewRect = NO;
    [self presentViewController:testVC animated:YES completion:nil];
}

#pragma mark - <UIPopoverPresentationControllerDelegate>
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

popover主動消失,直接調用dismiss就可以了。

- (void)clickBtn:(UIButton *)aBtn {
    [self dismissViewControllerAnimated:YES completion:nil];
}

但是\color{red}{UIPopoverPresentationController}有個的地方需要注意,滑動觸摸顯示區域以外的區域是不會消失,只有\color{red}{點擊}才可以消失。這個點很僵硬,萬惡的產品是很難接受的!\color{red}{redd}
還有就是箭頭的大小,間距,顯示隱藏的動畫時間點等都難修改,不過我個人覺得系統自帶的控件本身就挺好看的。。。。。

自定義樣式

系統自帶的不合適就只能自己擼羅。。。


自定義樣式Up

自定義樣式Left

1.使用了一個三角形的圖片做箭頭,支持上下左右;
2.顯示內容contentView暴露出來是可以添加其他的UIView
3.contentView支持跳轉大小等。。。
4.支持顯示區域范圍的設施,超出范圍會自動移動到顯示范圍內。
5.上下會自動調整,左右會自動調整,不支持設置為Up自動調整為Right。
代碼傳送門

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容