ded
ded

Reputation: 1350

Swift: Append Custom UIView programmatically

This is a near duplicate of this other SO question, however I'm running into some issues that it makes it appear like I'm not doing it correctly. For reference, I followed this excellent tutorial on creating re-usable views from a custom class and xib file (it's only a few minutes :) and I have no problems at all dragging that into another view onto my storyboard (as demonstrated at the end of the video)

Nevertheless for my case — I'm trying to call my custom class programmatically, and add it as a subview to one of my ScrollView instances.

class MainController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        first.directionalLockEnabled = true
        first.pagingEnabled = true
        var item = MyCustomView(frame: CGRectMake(0, 0, self.view.frame.width, 200))
        self.scrollView.addSubview(item)
    }

}

My Custom view looks like this:

import UIKit

class MyCustomView: UIView {
    @IBOutlet var view: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var dressTitle: UILabel!
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        NSBundle.mainBundle().loadNibNamed("MyCustomView", owner: self, options: nil)
        self.view.frame = bounds
        self.addSubview(self.view)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)

    }
}

There is an associated .xib file with it too that has the label and image.

So my question is, my view never appears in my ScrollView. I've double checked the constraints on my scroll view... I can even append simple UIView's with obvious visible dimensions CGRectMake(0, 0, 100, 100)... and nothing ever gives. What am I missing?

Upvotes: 3

Views: 4365

Answers (1)

ded
ded

Reputation: 1350

With some messing around I accidentally got it to work by duplicating the loadFromNib method to a second initializer in the CustomView.swift file. As seen in the video tutorial posted in the original question it shows just one of the initializers.... but in my case I had to add extra code to the init(frame). Eg:

// once with a NSCoder
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    NSBundle.mainBundle().loadNibNamed("Item", owner: self, options: nil)
    self.view.frame = bounds
    self.addSubview(self.view)
}

// for this to work programmatically I had to do the same...
override init(frame: CGRect) {
    super.init(frame: frame)
    NSBundle.mainBundle().loadNibNamed("Item", owner: self, options: nil)
    self.view.frame = bounds
    self.addSubview(self.view)
}

Upvotes: 4

Related Questions