AR Tunes
AR Tunes

Reputation: 15

How to set the positions and size of custom XIB View into the main View Controller?

I made custom view class with xib and load this UIView Class from XIB. It shows this xib but not set the height and width as of UIView in the ViewController.swift.

Output

CustomView.swift

class CustomView: UIView {

    @IBOutlet weak var contentView: UIView!

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

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

    func setupView() {
        Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
        self.addSubview(contentView)
    }

}

CustomView.xib Image

ViewController.Swift

Class ViewController: UIViewController {
        @IBOutlet weak var view1: UIView!

        override func viewDidLoad() {
            super.viewDidLoad()

            let customView = CustomView()
            customView.frame = view1.frame
            view1.addSubview(customView)
        }
    }

ViewController Image

Upvotes: 0

Views: 729

Answers (1)

Snezhana
Snezhana

Reputation: 100

I would go here with a little bit different approach in the initialization of the custom view. Here is the code:

CustomView:

class CustomView: UIView {

    @IBOutlet weak var contentView: UIView!

    class func instanceFromNibWithFrame(_ frame: CGRect) -> UIView {
        guard let view = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as ?UIView else {
            fatalError("CustomView can't be init")
        }
    view.frame = frame
    return view
    }
}

ViewController:

class ViewController: UIViewController {
    @IBOutlet weak var view1: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let customView = CustomView.instanceFromNibWithFrame(view1.bounds)
        view1.addSubview(customView)
    }
}

Upvotes: 1

Related Questions