iOS - how to add action in new line in UIAlertConroller swift

Viewed 1894

I need to add action in new line just like: alertActionsWithNewLines

I'm trying this code:

let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .alert)
    uncheckInAlert.setTitleImage(UIImage(named: "fail_Icon"))
    uncheckInAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
        self.userUncheckIn()
    }))
    uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    self.present(uncheckInAlert, animated: true, completion: nil)

But as result I have something like: alertActionsInOneLine. If action title is large then action automatically carried over on new line. With small action title, actions is grouped in one line. Is there any a ways to do this?

3 Answers

There is no flag you can set in order to change how Apple lays out its alert buttons. The UIAlertController with style alert will, however, change it's button layout automatically to vertical when it cannot properly fit the entire string of the button's text in a horizontal layout. So if your button's text is long enough, it will change the layout.

Though this is a solution to your question, I don't recommend adding arbitrary spaces or unnecessarily long strings to the button's text just so Apple will layout the buttons vertically in a production app. It's misusing the standard components and could easily start breaking down once strings become localized to other languages. In order to naturally achieve the desired behavior I would suggest creating your own, custom view to display buttons vertically.

Try change style form .alert to .actionSheet

Like in this code

let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .actionSheet)

Changing these lines from

uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

To

uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))

let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .alert)

To

let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .actionSheet)

This will show cancel option grouped with other options.

Related