前言
最近項目有一個需求需要實現一個類似氣泡的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];
}
但是有個的地方需要注意,滑動觸摸顯示區域以外的區域是不會消失,只有
才可以消失。這個點很僵硬,萬惡的產品是很難接受的!
還有就是箭頭的大小,間距,顯示隱藏的動畫時間點等都難修改,不過我個人覺得系統自帶的控件本身就挺好看的。。。。。
自定義樣式
系統自帶的不合適就只能自己擼羅。。。
自定義樣式Up
自定義樣式Left
1.使用了一個三角形的圖片做箭頭,支持上下左右;
2.顯示內容contentView暴露出來是可以添加其他的UIView
3.contentView支持跳轉大小等。。。
4.支持顯示區域范圍的設施,超出范圍會自動移動到顯示范圍內。
5.上下會自動調整,左右會自動調整,不支持設置為Up自動調整為Right。
代碼傳送門