ebby94
ebby94

Reputation: 3152

Creating a popup with UIView when a cell is tapped in UITableView Swift

I have a tableview and if a cell is tapped on the tableview, I want to create a UIView to pop up over the tableview and display the contents in the tableview cell. I want to add the code in tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) so that the UIView is opened when I select a row. I just need to know how to create a popup with UIView. I couldn't find any source which helped me out with this. A bit of explanation on how to do this will be awesome. Thanks in advance!

Upvotes: 1

Views: 8415

Answers (3)

Lee
Lee

Reputation: 848

First add let vw = UIView(), then try this

    vw.frame = CGRectMake(150, 150, 0, 0)
    vw.backgroundColor = UIColor.redColor()
    self.view.addSubview(vw)

    UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {

        self.vw.frame = CGRectMake(75, 75, 300, 300)

    }, completion: nil)

First create a UIView, and set its X and Y point(150), then width and height (300). I just simply add a background color to show that it is really there. Then the animatedWithDuration part is to reset the frame so it looks like pop up.

add this if you want the view behind become darker.

view.backgroundColor = UIColor(white: 1, alpha: 0.5)

As for touching background view to close the pop up view. You need a tap gesture recogniser, and function for it

    var tap = UITapGestureRecognizer()
    tap.delegate = self
    tap.addTarget(self, action: "tapped")
    self.view.addGestureRecognizer(tap)

then for its function

    func tapped(){
       vw.removeFromSuperview()
    }

Upvotes: 2

Anbu.Karthik
Anbu.Karthik

Reputation: 82766

Step-1

create one UIView set the frame as View.bounds at the same time add the Tap gesture for hide function.

Step-2

for present the view on click, use

UIView.animateWithDuration(1.0, animations: {
    yourView.alpha = 1.0
})

Step-3

on hide

 UIView.animateWithDuration(1.0, animations: {
    yourView.alpha = 0.0
})

finally if you want to hide use hidden or removefromsuperview

Upvotes: 2

user6005
user6005

Reputation: 75

If you are using IOS 8 or later you can just create UIView in the new UIViewController with setting attribute ModalPresentationStyle with value UIModalPresentationStyle. Something like this in you didSelectRowAtIndexPath:

var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSizeMake(500,600)
popover.delegate = self
popover.sourceView = self.view
popover.sourceRect = CGRectMake(100,100,0,0)

self.presentViewController(nav, animated: true, completion: nil)

Upvotes: 2

Related Questions