I am wondering what is the cleanest way to initialize a custom UIView
with a specific frame.
The UIView
is designed from a XIB
file.
Here is my implementation :
class CustomView : UIView {
@IBOutlet var outletLabel: UILabel!
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
private func setupView() {
// Set text for labels
}
}
Here is how I want to initialize it in my ViewController :
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let frame = CGRect(x: 0, y: 0, width: screenWidth - 50, height: 70)
let customView = CustomView.init(frame: frame)
But it is not working, I have a white UIView without any outlets.
And if I do this instead :
// Extension to UIView to load Nib
let customView : CustomView = UIView.fromNib()
I can see my view
from XIB
file, with its width/height used in the Interface Builder
.
What is I want to load the view
from XIB
file BUT with specific frame ?
Am I missing something about initialization ?
You can have a NibLoading class like:
Then your view will subclass the NibLoadingClass like:
Set your XIB class in File's Owner like: In this case it will be
YourUIView
Then instantiate it:
You can create custom class like this...
Initialize view where you want...