Monday, October 5, 2015

UIAlertControllerStyle.ActionSheet - Action Sheet since iOS 8

UIActionSheet is deprecated in iOS 8. To use the ActionSheet, it is required to use UIAlertController with UIAlertControllerStyle.ActionSheet.

Now edit ViewController.swift as:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myButton = UIButton(frame: CGRectMake(50, 50, 100, 30))
        myButton.setTitle("Press", forState: UIControlState.Normal)
        myButton.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        myButton.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)//Set the title color while highlighted
        myButton.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(myButton)
    }
    
    func btnPressed(sender: UIButton) {
        println("btnPressed")
        
        let myController = UIAlertController(title: "My Title", message: "My Message", preferredStyle: UIAlertControllerStyle.ActionSheet)
        myController.addAction(UIAlertAction(title: "Option 1", style: UIAlertActionStyle.Default, handler: { action in
            println("Option 1")
        }))
        myController.addAction(UIAlertAction(title: "Option 2", style: UIAlertActionStyle.Default, handler: { action in
            println("Option 2")
        }))
        myController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
        presentViewController(myController, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

The result is:


No comments:

Post a Comment