Xamarin.ios Закрыть лист действий UIAlertController при нажатии на экран - PullRequest
0 голосов
/ 02 июля 2018

Я создаю UIAlertController со стилем ActionSheet:

UIAlertController actionSheetAlert = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet);

Я добавляю к нему действие:

UIAlertAction alertAction = UIAlertAction.Create("Action", UIAlertActionStyle.Default, DoSomting);
var alertImage = UIImage.FromBundle("image")
                 .ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
alertImage = ResizeImage(sortingAlertImage, 32, 32)
                 .ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
alertAction.SetValueForKey(alertImage, new NSString("image"));
alertAction.SetValueForKey(UIColor.Black, new NSString("titleTextColor"));
actionSheetAlert.AddAction(alertAction);

И отобразить это:

PresentViewController(_actionSheetAlert, true, null);

Как закрыть UIAlertController при нажатии на экран?

Я могу сделать это, добавив действие «отмена», например:

var cancelAlertAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null);
cancelAlertAction.SetValueForKey(UIColor.Black, new NSString("titleTextColor"));
actionSheetAlert.AddAction(cancelAlertAction);

Но я не хочу отображать действие отмены.

Ответы [ 3 ]

0 голосов
/ 04 июля 2018

Хотя предложение Хуссейна работает в действительно базовой обстановке, оно может помешать, когда у вас есть другие виды под предупреждением с прикрепленными распознавателями жестов. Что я обычно делаю в подобных ситуациях (хорошо работает, например, при закрытии клавиатуры), это добавление полноэкранной невидимой кнопки в мое представление контента.

public readonly UIButton CloseButton;

public MyView()
{
    CloseButton = new UIButton(UIButtonType.System);
    CloseButton.Alpha = 0; //or CloseButton.Hidden = true;

    AddSubview(CloseButton);
}

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

UIAlertController actionSheetAlert;

public override void ViewDidAppear(bool animated)
{
    contentView.CloseButton.TouchUpInside += CloseAlert;
}

void CloseAlert(object sender, EventArgs e)
{
    //Notice the missing null check because the alert should never be null here. If it is you have a problem in your code and you'll find it easily.

    actionSheetAlert.DismissViewController(true, () => { });

    //Hide the button here.
}

А когда вы открываете диалоговое окно с предупреждением, вы просто делаете кнопку видимой. Если вы хотите проявить фантазию и прояснить для пользователя, что нажатие за пределами диалогового окна закрывает ее, тогда вы можете сделать кнопку черной и установить альфа на 30% при открытии диалогового окна.

void OpenDialog() {
    //Create dialog, add actions etc.

    UIView.Animate(0.3, () => { CloseButton.Alpha = 0.3f});
}

И если вы удерживаете кнопку отмены в предупреждении, не забудьте также скрыть там кнопку закрытия с Hidden = true или Alpha = 0.

0 голосов
/ 09 июля 2018

Нашли решение благодаря https://forums.xamarin.com/profile/LandLu:

UIAlertController actionSheetAlert = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet);

PresentViewController(actionSheetAlert, true, () => {
UITapGestureRecognizer recognizer = new UITapGestureRecognizer((tapRecognizer) =>
{
    actionSheetAlert.DismissViewController(true, null);
});
// After testing, The first subview of the screen can be used for adding gesture to dismiss the action sheet
actionSheetAlert.View.Superview.Subviews[0].AddGestureRecognizer(recognizer);
});
0 голосов
/ 02 июля 2018

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

func showAlertBtnClicked(sender: UIButton) {
    let alert = UIAlertController(title: "This is title", message: "This is message", preferredStyle: .Alert)
    self.presentViewController(alert, animated: true, completion:{
        alert.view.superview?.userInteractionEnabled = true
        alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
    })
}

func alertControllerBackgroundTapped()
{
    self.dismissViewControllerAnimated(true, completion: nil)
}

Оповещение не может быть отклонено как обычно. Или создайте пользовательский вид оповещения.

...