Volkan Sonmez
Volkan Sonmez

Reputation: 785

How to add custom view xib file dynamically

I am beginner. Thank you for help. I want to add a custom view to scrollview. I have to set label text but can't do because it's nil. I tried this way.

var y = 50;
self.scrollView.contentSize = CGSize(width: 350, height: 200);
for i in 0...10
{
    let view = MyView2();
    view.translatesAutoresizingMaskIntoConstraints = false;
    view.frame = CGRect(x: 100, y: y, width: 300, height: 100);
    y = y + 150;
    view.lblName.text = "Test : \(i)";
    self.scrollView.contentSize = CGSize(width: 350, height: y);
    self.scrollView.addSubview(view); 
}

This is my customView. I added xib file and I am sure I choose xib file custom class.

class MyView2: UIView {
    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var myButton: UIButton! 
}

Upvotes: 0

Views: 259

Answers (1)

Pramod Shukla
Pramod Shukla

Reputation: 235

Initialise the view like that-

 let view = UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView

Upvotes: 2

Related Questions