Created
November 1, 2017 15:28
-
-
Save nrlnishan/2802d9434ae893f71b4af170c7fc36ef to your computer and use it in GitHub Desktop.
Creating a custom UIView using Xib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Steps for creating custom UIView. | |
1. Create a xib file, eg: MyCustomView.xib | |
2. Do necessary layout in xib file | |
3. Create a UIView file. eg: MyCustomView.swift. | |
4. Set this MyCustomView.swift file as the file owner of that xib | |
5. Create necessary outlets from the .xib file to .swift file. Important: Create one outlet for the root parent UIView to .swift file. | |
Name this outlet as as containerView | |
6. Override both the init method i.e using decoder & frame | |
7. Set the code as follows | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
setupXib() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
setupXib() | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
self.containerView.frame = bounds | |
} | |
func setupXib() { | |
// 1. Load the nib | |
self.containerView = Bundle.main.loadNibNamed(WorkoutSetInputView.stringIdentifier, owner: self, options: nil)![0] as! UIView | |
// 2. Set the bounds for the container view | |
self.containerView.frame = bounds | |
self.containerView.autoresizingMask = [.flexibleWidth,.flexibleHeight] | |
// 3. Add this container view as the subview | |
addSubview(containerView) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment