Present a ViewController as a popover

3.4k views Asked by At

I have a main ViewController in which I have a tableView with custom tableViewCell, inside of it I have added a few view objects and a button. I want to present an another ViewController when I clicked on the button in the cell and also I need to send (tableCell data where the click event occurred) and Receive (selected value from the pickerView and other label's text) from the popped ViewController then finally I need a way (like a close button) to close it.

I am able to send the data of the cell where the click event occurred in the cell using the following code

@IBAction func cellBtnClicked(_ sender: Any) {
    let foodItem:FoodItem?
    let indexPath : IndexPath
    if let button = sender as? UIButton {
        let cell = button.superview?.superview as! UITableViewCell
        indexPath = self.tableView.indexPath(for: cell)!
        let hotel =  hotels[indexPath.section]
        foodItem = hotel.menu[indexPath.row]

then I am loading that cell data into the popover controller and trying to present it as a popover

let popoverContent = self.storyboard?.instantiateViewController(withIdentifier:"ShowPopoverVC" ) as! MiniCartVC
        popoverContent.foodItem = foodItem
        popoverContent.modalPresentationStyle = UIModalPresentationStyle.popover

                if let popover = popoverContent.popoverPresentationController {

                    let viewForSource = sender as! UIView
                    popover.sourceView = viewForSource

                    // the position of the popover where it's showed
                    popover.sourceRect = viewForSource.bounds

                    // the size you want to display
                    popoverContent.preferredContentSize = CGSize(width: 200, height: 135)
                    popover.delegate = self
                }            

                self.present(popoverContent, animated: true, completion: nil)
    }

But it is not coming as a popover instead like a segue, expanding the entire View.Also I need a way to send the data from popover VC to the MainVC upon dismissing it.

Kindly let me know if there is any way to implement it properly. Any resource as a reference purpose is also fine, thanks.

1

There are 1 answers

3
soumil On

From your listed code :

popover.delegate = self

You have set the UIPopoverPresentationControllerDelegate to be self. Just implement the optional method and use this implementation

func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
}