Download custom UIView from xib programmatically

I created a custom UIView in MySample.xib. I added a class MyViewto File Ownerfor xib.

Myview.swift

class MyView: UIView {

    @IBOutlet var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    func setup() {
        NSBundle.mainBundle().loadNibNamed("MySample", owner: self, options: nil)            
        self.addSubview(self.view)
    }
}

Now I load this file MyViewfrom MyControlleras follows:

Mycontroller.swift

class MyController: UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)

        view.addSubview(MyView())

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Now, to display this view, I am using the following code from another controller UIButton:

presentViewController(MyController(), animated: true, completion: nil)

This displays the view on the screen. But the problem is that it does not accept any user interaction. In my user view, I have a UITableView that displays data, but it does not scroll or retrieve due to lack of user interaction.

Any idea what I'm doing wrong?

+4
2

.

, , xib , :

  • xib , init, xib init init UIView(), , , init MyView.

  • xib , , IB, , ( , MyView).

  • :

    class MyController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //Get all views in the xib
            let allViewsInXibArray = NSBundle.mainBundle().loadNibNamed("MySample", owner: self, options: nil)
    
            //If you only have one view in the xib and you set it class to MyView class
            let myView = allViewsInXibArray.first as! MyView
    
            //Set wanted position and size (frame)
            myView.frame = self.view.bounds
    
            //Add the view
            self.view.addSubview(myView)
    
            //TODO: set wanted constraints.
        }
    }
    
+8

xib File Owner class MyView, xib MyView. , @Oleg Sherman, MyView() , , this class is not key value coding-compliant for the key ****.:

let allViewsInXibArray = NSBundle.mainBundle().loadNibNamed("MySample", owner: MyView(), options: nil)

File Owner class to MyView , xib Storyboard.

, File Owner MyView xib , .

0

All Articles