swifttableviewxibsubviewcentralized

how to create xib subview at the center of tableview swift


I have tableview and I created the custom xib uiview as "detailview" for it. I want to show this detailview at the center of scrolled area when tapped to tableview cell. I can show this view but cannot centralized it. when I set value to frame manually, subview will be at center (approximately) but when I tap the cell which is at the bottom, the subview is appearing at the top of page and also it is moving when i scroll the tableview.

Please help me to show this view at the center of the scrolled area and be fixed

Here is my codes;

Detail View :

class TopTenDetailView: UIView {

      var screenWidth:CGFloat = UIScreen.mainScreen().bounds.width*0.08
      var screenHeight :CGFloat = UIScreen.mainScreen().bounds.height*0.08

      class func instanceFromNib() -> UIView {
            return UINib(nibName: "TopTenDetail", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
      }

      override func awakeFromNib() {
            super.awakeFromNib()
            self.layer.cornerRadius=10

            let testFrame : CGRect = CGRectMake(screenWidth,screenHeight,320,480)
            self.frame = testFrame
            self.userInteractionEnabled=true
      }

      @IBAction func close(sender: UIButton) {
            self.hidden=true
      }
}

And TableViewController's method ;

      override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
             var detailView = TopTenDetailView.instanceFromNib
             self.view.addSubview(detailView())
      } 

Solution

  • The way this is setup has many problems and i would be surprised if it actually ever works as intended.

    A much better, simpler setup uses a OverFullScreen presentation style and it goes like this:

    enter image description here enter image description here

    Ok, now for the code:

        // MARK : - UITableViewDelegate
        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            self.performSegueWithIdentifier("detailSegue", sender: self)
        }
    
        // MARK: - segues
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if let vc = segue.destinationViewController as? UIViewController{
                vc.modalPresentationStyle = .OverFullScreen
    
            }
        }
    

    The OverFullScreen presentation style uses a proper UIViewController modal segue but leaves the presenting UIViewController visible under the presented one.

    You can then just layout whatever you want on DetailViewController using Interface Builder and autolayout without having to do hacky match calculations on the layout at runtime.

    Hope it helps!

    enter image description here enter image description here