Why is my popup view is empty?

烈酒焚心 提交于 2019-12-11 18:41:32

问题


I am trying to make a popup view similar to this one. What I have done so far is:

  • Open a new single view project.
  • Added a button to the main view.
  • Added a new xib file named "popup.xib"
  • Added a new swift file named "PopupViewController.swift"
  • At the identity tab I made the first responders class to be "PopupViewController"
  • I put in the popup.xib a label, a button and a view with different background colour. Of course everything has constraints about where it should appear.

My code:

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBAction func showPopup(sender: AnyObject) {
        var x = PopupViewController()
        x.show(self.view)
        x.showAnimate()
    }
}

PopupViewController

import UIKit

class PopupViewController : UIViewController {

    func show(tView : UIView) {
        tView.addSubview(self.view)
        println("here")
        self.view.backgroundColor = UIColor.redColor()

    }

    func showAnimate() {
        self.view.transform = CGAffineTransformMakeScale(1.0, 1.0)
        self.view.alpha = 0.3
    }

}

The result: When the button is pressed I get a redish overlay on the view (because the view I added is red and has 30% opacity), but the new view is empty. No button, no label, no area with different colour.

What do I have to do to make the popup.xib show it's elements?


Update

I was missing the connection between the File's Owner and the main view in addition to Nerkyators answer. Just right click the "File's Onwer" and from view drag to the main view that is two lines below it.


回答1:


You need to load manually the xib associated to your view. I use this extensions (found at this link) modified to support UIViewController and then I call it when needed.

extension UIViewController {
    class func loadFromNibNamed(nibNamed: String, bundle : NSBundle? = nil) -> Self? {
        return UINib(
            nibName: nibNamed,
            bundle: bundle
            ).instantiateWithOwner(nil, options: nil)[0] as? UIViewController
    }
}

then

@IBAction func showPopup(sender: AnyObject) {
    var x = PopupViewController.loadFromNibNamed("popup")
    //do what you need with x
}


来源:https://stackoverflow.com/questions/28275302/why-is-my-popup-view-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!