如何添加UIActionSheet按钮复选标记?

我想知道如何在actionSheet按钮右侧添加复选标记最简单的方法? Bellow是Podcasts应用程序的屏幕截图。

在此处输入图像描述

最后我通过使用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]; 

这就是结果:

UIActionSheet按钮复选标记

尝试这个技巧:

  • 了解如何将ViewController显示为弹出窗口
    • 将UITable添加到ViewController
    • 在UITable中显示项目
    • 通过添加自定义单元格来自定义UITable
    • 在每个自定义单元格中添加一个按钮
    • 该按钮将有两种图像,一个是空白框,另一个是带有复选标记的框
    • 当用户触摸表格单元格时,您需要更改与该表格行对应的按钮图像,以便用户认为他们正在检查或取消选中该框
    • 最后在底部添加一个完成按钮以关闭viewcontroller

谷歌所有这些项目的教程。 正如我所说,这不是一项简单的任务,因为Xcode中没有开箱即用的复选标记function。

来自: https : //stackoverflow.com/a/40542931/3901620

另一种选择是在按钮标题上添加一个复选标记字符,如“标题✓”。 它将在标题旁边,而不是在按钮的右侧,但我认为这不是一个非常大的问题。

Swift版本:4.1

我使用UIAlertController创建扩展来实现这个实现。

 extension UIAlertController { static func actionSheetWithItems(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 } 

}

执行:

  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) } 

最后结果:

选择性别

希望有所帮助!

谢谢