Swift - Add Custom Xib View As Subview Programmatically

Ive created a custom xib that was previously used in my storyboard, and I just want to create an instance of a custom view size, and then add it as a subtitle to uiscrollview. Ive tried using this block of code in the viewdidload function of my view controller.

let cardView = CardView(coder: NSCoder()) cardView!.frame.size.width = 100 cardView!.frame.size.height = 100 scrollView.addSubview(cardView!) 

but i get this error

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -containsValueForKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!' 

EDIT: this is the code for the fast file connected to CardView.xib

 import UIKit class CardView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var cornerView: UIView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NSBundle.mainBundle().loadNibNamed("CardView", owner: self, options: nil) self.addSubview(view) view.frame = self.bounds cornerView.layer.cornerRadius = 3 cornerView.layer.masksToBounds = true view.layer.shadowOffset = CGSizeMake(1, 5); view.layer.shadowRadius = 2; view.layer.shadowOpacity = 0.2; view.layer.masksToBounds = false } } 

instead of using auto-layout, I tried just adjusting the height and width to verify adding subviews manually from these two lines (also just head up, I'm new to iOS development)

 cardView!.frame.size.width = 100 cardView!.frame.size.height = 100 
0
source share
1 answer

What I used when using custom XIB initialization for presentation below.

In the presentation class, as with your CardView, the code looks like.

 class CardView: UIView { @IBOutlet weak var cornerView: UIView! func setupWithSuperView(superView: UIView) { self.frame.size.width = 100 self.frame.size.height = 100 superView.addSubview(self) cornerView = UIView(frame: self.bounds) cornerView.layer.cornerRadius = 3 cornerView.layer.masksToBounds = true view.layer.shadowOffset = CGSizeMake(1, 5); view.layer.shadowRadius = 2; view.layer.shadowOpacity = 0.2; view.layer.masksToBounds = false } } 

and where you call this class to initialize, use this.

 let cardView = NSBundle.mainBundle("CardView").loadNibNamed("", owner: nil, options: nil)[0] as! CardView cardView.setupWithSuperView(scrollView) 

Try it once. But make sure that the first view of the xib file is of type CardView. I mean the class of the first kind - CardView.

0
source

Source: https://habr.com/ru/post/1012274/


All Articles