I'm wondering how I can create a popover with buttons like this.
ANSWER:
UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: nil
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: @"Take Photo",
@"Choose Existing Photo", nil];
[actionSheet showFromRect: button.frame inView: button.superview animated: YES];
Somewhere else in your delegated object class...
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
// take photo...
}
else if (buttonIndex == 1) {
// choose existing photo...
}
}
This is a UIActionSheet
. On the iPhone, it animates in from the bottom. On the iPad it appears in a popover.
Assuming you're doing this on the press of a button:
UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle: nil
delegate: self
cancelButtonTitle: nil
destructiveButtonTitle: nil
otherButtonTitles: @"Take Photo",
@"Choose Existing Photo", nil];
[actionSheet showFromRect: button.frame inView: button.superview animated: YES];
In iOS8+, you should use the new UIAlertController
class:
UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
message: nil
preferredStyle: UIAlertControllerStyleActionSheet];
[alertController addAction: [UIAlertAction actionWithTitle: @"Take Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// Handle Take Photo here
}]];
[alertController addAction: [UIAlertAction actionWithTitle: @"Choose Existing Photo" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// Handle Choose Existing Photo here
}]];
alertController.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController * popover = alertController.popoverPresentationController;
popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
popover.sourceView = sender;
popover.sourceRect = sender.bounds;
[self presentViewController: alertController animated: YES completion: nil];
or in Swift
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
alertController.addAction(UIAlertAction(title: "Take Photo", style: .Default, handler: { alertAction in
// Handle Take Photo here
}))
alertController.addAction(UIAlertAction(title: "Choose Existing Photo", style: .Default, handler: { alertAction in
// Handle Choose Existing Photo
}))
alertController.modalPresentationStyle = .Popover
let popover = alertController.popoverPresentationController!
popover.permittedArrowDirections = .Up
popover.sourceView = sender
popover.sourceRect = sender.bounds
presentViewController(alertController, animated: true, completion: nil)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With