ios custom view example

1. Create a xib file. File -> New -> File -> Select View -> Next -> Name it CustomView -> Create.

2. Select this CustomView xib on the interface builder, in the attribute inspector, select the size to freeform.

3. Add a label and a button to the xib by dragging a label and a button from the object library and drop the into the xib file.

4. Create an UIView class for the custom xib file. File -> New -> File -> Select Cocoa Touch File -> Next -> Name it CustomView -> Select UIView in the subclass of field -> Create.

5. Connect the label and button from the xib file to the CustomView class, by Ctrl dragging them from the xib file to the CustomView swift class.

6. Select the CustomView xib file, on the left of the interface builder, there are 3 icons for file’s owner, first responder, and view, select the file’s owner and in the identity inspector, select CustomView for the class field.

7. This should be what it looks like in the CustomView.swift class.

import UIKit

class CustomView: UIView {

    @IBOutlet weak var randomNumLabel: UILabel!
    
    @IBAction func generate(_ sender: UIButton) {
        let random = Int(arc4random_uniform(100) + 1) // generate a random number between 0 and 100 inclusive
        randomNumLabel.text = String(random)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "CustomView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        
        view.frame = bounds
        view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        addSubview(view)
    }

}

8. In the storyboard, drag a View from the object library to the ViewController, and set its class to CustomView.

9. Command + R to run the app.

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search