tallt456
tallt456

Reputation: 49

Using custom uiview in viewcontroller

I'm trying to use a custom uiview that is in a xib file. I'm a beginner and don't know where to start. I have this so far, but I don't know what I should set my placeholder view equal to

edit: full viewController:

import UIKit

class Viewcontroller: UIViewController {

    
    @IBOutlet weak var placeholderView: UIView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        placeholderView = view
        
    }
    
    class func instanceFromNib() -> CustomView {
            let view = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomView
            return view
    }
    

Upvotes: 0

Views: 4456

Answers (1)

El Tomato
El Tomato

Reputation: 6707

A. Let me suppose that you have a xib file titled 'TestView.' Also let me suppose that you have a subclass file of UIView titled 'TestView.' B. Select your xib file. And select File's Owner. And set the class to TestView (the name of the subclass file). C. Open the xib file with Interface Builder. Select 'Custom View.' (in the middle pane) IBOutlet-Connect this view to your UIView swift file. For example, name it like the following. @IBOutlet var customView: NSView! D. This subclass file should have the following.

import UIKit

class TestView: UIView {
    @IBOutlet var contentView: UIView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    
    private func commonInit() {
        Bundle.main.loadNibNamed("TestView", owner: self, options: nil)
        addSubview(contentView)
        contentView.frame = self.bounds
    }
}

E. Open the storyboard. Drag and drop a Custom View onto the view controller scene. Under the identity inspect, set the class name to TestView. F. IBOutlet-connect the custom view object in the view controller like the following.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var testView: TestView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

That's all.

Upvotes: 1

Related Questions