6.4. AddExpenseViewController: UIMenu for buttonTakePhoto

The app so far

Now let's handle the actions for buttonTakePhoto (with the camera icon). If the user taps the button, it should display two options: "Camera" and "Gallery." If the user selects the "Camera" option, it will open the camera and take a photo; else, if the user selects "Gallery," it will open the image gallery to pick a photo. Finally, the chosen photo will be set as the image inside buttonTakePhoto.

Let's open AddExpenseViewController.swift file. and add the following code in it:

//
//  AddExpenseViewController.swift
//  App6
//
//  Created by Sakib Miazi on 5/18/23.
//

import UIKit

class AddExpenseViewController: UIViewController {
    
    //Codes omitted...
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
       //codes omitted...
        
        //MARK: adding menu to buttonTakePhoto...
        addExpenseScreen.buttonTakePhoto.menu = getMenuImagePicker()
        
        //codes omitted...
    }
    
    //codes omitted...
    
    func getMenuImagePicker() -> UIMenu{
        var menuItems = [
            UIAction(title: "Camera",handler: {(_) in
                self.pickUsingCamera()
            }),
            UIAction(title: "Gallery",handler: {(_) in
                self.pickPhotoFromGallery()
            })
        ]
        
        return UIMenu(title: "Select source", children: menuItems)
    }
    
    //MARK: take Photo using Camera...
    func pickUsingCamera(){
        
    }
    
    //MARK: pick Photo using Gallery...
    func pickPhotoFromGallery(){
        
    }
    //codes omitted...

}

Here we are writing getMenuImagePicker() -> UIMenu method to create a pop-up menu for displaying the options. In the closures, we call two methods, pickUsingCamera() and pickPhotoFromGallery() to handle the option clicks.

Modify the buttonTakePhoto in AddExpenseView

Now we need to set the menu as the primary action for buttonTakePhoto. Open AddExpenseView.swift and add the following line to the method setupbuttonTakePhoto():

Let's run the app now.

Our next task is to implement the Gallery and Camera functions.

Last updated

Was this helpful?