示例代码
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view.backgroundColor = [UIColor whiteColor];
if (@available(iOS 16.0, *)) {
modalViewController.modalPresentationStyle = UIModalPresentationPageSheet;
// iOS 15 提供 SheetPresentation
UISheetPresentationController *sheet = modalViewController.sheetPresentationController;
// iOS 16 支持为 SheetPresentation 自定义高度
UISheetPresentationControllerDetent *customDetent = [UISheetPresentationControllerDetent customDetentWithIdentifier:@"customDetent" resolver:^CGFloat(id<UISheetPresentationControllerDetentResolutionContext> context) {
// 根据上下文的信息来调整高度
return SGScreen_Height - 200;
}];
if (sheet) {
sheet.detents = @[
[UISheetPresentationControllerDetent mediumDetent],
[UISheetPresentationControllerDetent largeDetent],
customDetent
];
sheet.prefersGrabberVisible = YES;
sheet.selectedDetentIdentifier = @"customDetent";
sheet.prefersScrollingExpandsWhenScrolledToEdge = NO;
}
} else {
// Fallback on earlier versions
modalViewController.modalPresentationStyle = UIModalPresentationAutomatic;
}
[self presentViewController:modalViewController animated:YES completion:nil];
UISheetPresentationController
是 iOS 15 及以上版本中引入的一种用于呈现底部弹出视图(Sheet)的控制器,提供了一种标准化的方式来管理模态视图的展示。在 iOS 16 及以上版本中,UISheetPresentationController
更加强大,允许开发者通过 customDetentWithIdentifier:resolver:
方法自定义弹出视图的高度。