How to add UIActionSheet button check mark?
Note that the solution can crash in a future update to iOS. I'm accessing undocumented private APIs. Such solutions are very fragile. Please see the comments below.
Finally I got the answer by using UIAlertController:
UIAlertController *customActionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *firstButton = [UIAlertAction actionWithTitle:@"First Button" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
//click action
}];
[firstButton setValue:[UIColor blackColor] forKey:@"titleTextColor"];
[firstButton setValue:[UIColor blackColor] forKey:@"imageTintColor"];
[firstButton setValue:@true forKey:@"checked"];
UIAlertAction *secondButton = [UIAlertAction actionWithTitle:@"Second Button" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
//click action
}];
[secondButton setValue:[UIColor blackColor] forKey:@"titleTextColor"];
UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
//cancel
}];
[cancelButton setValue:[UIColor blackColor] forKey:@"titleTextColor"];
[customActionSheet addAction:firstButton];
[customActionSheet addAction:secondButton];
[customActionSheet addAction:cancelButton];
[self presentViewController:customActionSheet animated:YES completion:nil];
And this is the result:
Swift Version: 4.1
I came across this implementation using creating extension over UIAlertController.
extension UIAlertController {
static func actionSheetWithItems<A : Equatable>(items : [(title : String, value : A)], currentSelection : A? = nil, action : @escaping (A) -> Void) -> UIAlertController {
let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
for (var title, value) in items {
if let selection = currentSelection, value == selection {
// Note that checkmark and space have a neutral text flow direction so this is correct for RTL
title = "✔︎ " + title
}
controller.addAction(
UIAlertAction(title: title, style: .default) {_ in
action(value)
}
)
}
return controller
}
}
Implementation:
func openGenderSelectionPopUp() {
let selectedValue = "Men" //update this for selected value
let action = UIAlertController.actionSheetWithItems(items: [("Men","Men"),("Women","Women"),("Both","Both")], currentSelection: selectedValue, action: { (value) in
self.lblGender.text = value
})
action.addAction(UIAlertAction.init(title: ActionSheet.Button.cancel, style: UIAlertActionStyle.cancel, handler: nil))
//Present the controller
self.present(action, animated: true, completion: nil)
}
Final Result:
Hope that helps!
Thanks