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

Jar*_*Chu 11 objective-c uiactionsheet ios

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

在此输入图像描述

Jar*_*Chu 35

最后我通过使用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];
Run Code Online (Sandbox Code Playgroud)

这就是结果:

UIActionSheet按钮复选标记

  • 请注意,您的解决方案可能会在未来的 iOS 更新中崩溃。您正在访问未记录的私有 API。这种解决方案非常脆弱。 (2认同)

Har*_*ngh 7

迅捷版:4.1

我通过在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
}
Run Code Online (Sandbox Code Playgroud)

}

实现方式:

   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)
}
Run Code Online (Sandbox Code Playgroud)

最后结果:

选择性别

希望有帮助!

谢谢