Adarkuccio
Adarkuccio

Reputation: 973

Using Swift, how to create a UIViewController over another one using StoryBoards

I have a viewcontroller that hold a button for now, and I want to create a new viewcontroller and add his view over the current one

So far I did this:

class ViewController : UIViewController
{
    var myController: MyController = MyController.controller()

    init(coder aDecoder: NSCoder!)
    {
        super.init(coder: aDecoder)
    }

    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
    {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.view.addSubview(self.myController.view)
    }

    @IBAction func buttonPressed(sender : AnyObject)
    {

    }
}

in MyController I did a singleton (I hope I did it right)

class MyController : UIViewController
{

    init(coder aDecoder: NSCoder!)
    {
        super.init(coder: aDecoder)
    }

    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
    {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    class func controller() -> MyController
    {
        var once : dispatch_once_t = 0
        var sharedInstance: MyController?

        dispatch_once(&once, { sharedInstance = MyController()})

        return sharedInstance!
    }
}

the behavior I got is this, if I DON'T call the

self.view.addSubview(self.myController.view)

everything works fine, if I did, the button in the center is not anymore recognizing the touches, it is like it has something over that intercept the touch, what is wrong here? what I'm missing?

Upvotes: 2

Views: 4220

Answers (1)

Anil Varghese
Anil Varghese

Reputation: 42977

in MyController I did a singleton (I hope I did it right)

You did it wrong. Singleton is not required here. If you are using storyboard, the below line

var myController: MyController = MyController.controller()  

could be

var myController: MyController = self.storyboard.instantiateViewControllerWithIdentifier("MyViewController")

Then before adding sub view set the frame of the self.myController.view

self.myController.view.frame = CGRectMake(0, 0, 320, 200); // or what ever frame you want

Upvotes: 1

Related Questions