Подтвердить что ты не робот

Как добавить контрольную отметку кнопки UIActionSheet?

Интересно, как добавить галочку справа от кнопки ActionSheet простейшим способом? Ниже приведен скриншот приложения Подкасты.

введите описание изображения здесь

4b9b3361

Ответ 1

Обратите внимание, что решение может дать сбой в будущем обновлении для iOS. Я получаю доступ к недокументированным закрытым API. Такие решения очень хрупкие. Пожалуйста, смотрите комментарии ниже.

Наконец, я получил ответ с помощью 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 button check mark

Ответ 2

Swift Версия: 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
}

}

Реализация:

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

Конечный результат:

Select Gender

Надеюсь, это поможет!

Спасибо

Ответ 3

Другой вариант - просто добавить символ галочки в заголовок кнопки, например, "Заголовок ✓". Это будет рядом с названием, а не с правой стороны кнопки, но я думаю, что это не очень большая проблема.

Ответ 4

Попробуйте этот трюк:

  • Узнайте, как показать ViewController как всплывающее окно
    • Добавить UITable в ViewController
    • Показать элементы в UITable
    • Настроить UITable, добавив пользовательские ячейки
    • В каждой из пользовательских ячеек добавить кнопку
    • Эта кнопка будет иметь два вида изображений, один пустой ящик и другой блок с галочкой
    • Когда пользователь прикасается к ячейке таблицы, вам нужно изменить изображение кнопки, соответствующее этой строке таблицы, поэтому пользователь считает, что они проверяют или снимают флажок
    • и, наконец, добавьте кнопку "Готово" внизу, чтобы закрыть диспетчер просмотра

Google все эти элементы для учебных пособий. Как я уже сказал, это непростая задача, так как в Xcode нет функции проверки галочки.

От: fooobar.com/questions/1012399/...

Ответ 5

Быстрая реализация:

class Controller: UIViewController {

    var isFirstButtonChecked = true

    @IBAction func buttonTapped(_ sender: UIButton?) {
        let firstButton = UIAlertAction(title: "First Button", style: .default, handler: { [unowned self] _ in
            self.isFirstButtonChecked = true
            print("First Button tapped")
        })
        //Here the main magic; it called Key-Value Coding, or KVC:
        firstButton.setValue(isFirstButtonChecked, forKey: "checked")

        let secondButton = UIAlertAction(title: "Second Button", style: .default, handler: { [unowned self] _ in
            self.isFirstButtonChecked = false
            print("Second Button tapped")
        })
        secondButton.setValue(!isFirstButtonChecked, forKey: "checked")

        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        alert.addAction(firstButton)
        alert.addAction(secondButton)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
}

Вы также можете поставить галочку для большего количества кнопок, используя перечисление:

class Controller: UIViewController {

    enum ButtonChecked {
        case first
        case second
        case third
        case forth
    }

    var buttonChecked: ButtonChecked = .first

    @IBAction func buttonTapped(_ sender: UIButton?) {
        let firstButton = UIAlertAction(title: "First Button", style: .default, handler: { [unowned self] _ in
            self.buttonChecked = .first
            print("First Button tapped")
        })

        let secondButton = UIAlertAction(title: "Second Button", style: .default, handler: { [unowned self] _ in
            self.buttonChecked = .second
            print("Second Button tapped")
        })

        let thirdButton = UIAlertAction(title: "Third Button", style: .default, handler: { [unowned self] _ in
            self.buttonChecked = .third
            print("Third Button tapped")
        })

        let forthButton = UIAlertAction(title: "Forth Button", style: .default, handler: { [unowned self] _ in
            self.buttonChecked = .forth
            print("Forth Button tapped")
        })

        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        switch buttonChecked {
        case .first:
            firstButton.setValue(true, forKey: "checked")
        case .second:
            secondButton.setValue(true, forKey: "checked")
        case .third:
            thirdButton.setValue(true, forKey: "checked")
        case .forth:
            forthButton.setValue(true, forKey: "checked")
        }

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        alert.addAction(firstButton)
        alert.addAction(secondButton)
        alert.addAction(thirdButton)
        alert.addAction(forthButton)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
}