Swift - Add Custom Xib View As Subview Programmatically

北慕城南 提交于 2019-12-08 10:28:37

问题


Ive made a custom xib that I've used in my storyboard before and i want simply create an instance of the custom view adjust size and then add it as a subview to a uiscrollview. Ive tried using this block of code in the viewdidload func of my view controller

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

but I'm getting 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 swift 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 simply settings height and width to test adding subviews manually from these 2 lines(also just a heads up i am new to iOS development)

cardView!.frame.size.width = 100
cardView!.frame.size.height = 100

回答1:


What i have used in case of using custom XIB for view initialization is below.

In the class of the view like for you its CardView the code goes 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 are calling this class for initialization, use this.

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

Try this once. But make sure the first view of the xib file is of type CardView. I mean the class of the first view is CardView.



来源:https://stackoverflow.com/questions/39322772/swift-add-custom-xib-view-as-subview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!