Search code examples
iosswiftuitableviewnsrangeexception

Swift: NSRangeException when initializing UITableViewCells


I'm having some minor issues trying to get my UITableView to function correctly. This is what the error looks like:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

I've narrowed down the issue to this particular snippet of code: (Line 2)

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(String(TestCell), forIndexPath: indexPath)
    return cell
}

Full Swift File:

class ViewController: UITableViewController {

let closeHeight: CGFloat = 91
let openHeight: CGFloat = 166
var itemHeight = [CGFloat](count: 4, repeatedValue: 91.0)


override func viewDidLoad() {
    super.viewDidLoad()

    tableView.registerClass(TestCell.self, forCellReuseIdentifier: String(TestCell))
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemHeight.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(String(TestCell), forIndexPath: indexPath)
    return cell
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return itemHeight[indexPath.row]
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! FoldingCell

    var duration = 0.0
    if itemHeight[indexPath.row] == closeHeight { // open cell
        itemHeight[indexPath.row] = openHeight
        cell.selectedAnimation(true, animated: true, completion: nil)
        duration = 0.5
    } else {// close cell
        itemHeight[indexPath.row] = closeHeight
        cell.selectedAnimation(false, animated: true, completion: nil)
        duration = 1.1
    }

    UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { () -> Void in
        tableView.beginUpdates()
        tableView.endUpdates()
        }, completion: nil)

    }
}

EDIT 1:

class TestCell: FoldingCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    containerView = createContainerView()
    foregroundView = createForegroundView()

    // super class method configure views
    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func animationDuration(itemIndex: NSInteger, type: AnimationType) -> NSTimeInterval {

    // durations count equal it itemCount
    let durations = [0.33, 0.26, 0.26] // timing animation for each view
    return durations[itemIndex]
}
}

extension TestCell{

func createForegroundView() -> RotatedView{
    let foregroundView = RotatedView(frame: .zero)
    foregroundView.backgroundColor = UIColor.blackColor()
    foregroundView.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(foregroundView)

    foregroundView.topAnchor.constraintEqualToAnchor(foregroundView.superview?.topAnchor, constant: 25)
    foregroundView.leftAnchor.constraintEqualToAnchor(foregroundView.superview?.leftAnchor, constant: 25)
    foregroundView.widthAnchor.constraintEqualToAnchor(foregroundView.superview?.widthAnchor, constant: -50)
    foregroundView.heightAnchor.constraintEqualToConstant(100)

    let topConstraint = foregroundView.constraints[0]
    topConstraint.identifier = "ForegroundViewTop"
    foregroundView.layoutIfNeeded()
    return foregroundView
}

func createContainerView() -> UIView {
    let containerView = UIView(frame: .zero)
    containerView.backgroundColor = UIColor.grayColor()
    containerView.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(containerView)

    containerView.topAnchor.constraintEqualToAnchor(containerView.superview?.topAnchor, constant: 25)
    containerView.leftAnchor.constraintEqualToAnchor(containerView.superview?.leftAnchor, constant: 25)
    containerView.widthAnchor.constraintEqualToAnchor(containerView.superview?.widthAnchor, constant: -50)
    containerView.heightAnchor.constraintEqualToConstant(100)

    let topConstraint = containerView.constraints[0]
    topConstraint.identifier = "ContainerViewTop"
    containerView.layoutIfNeeded()

    return containerView
}
}

FYI:

I'm not using the default Interface Builder, I've written all the GUI-related code in the TestCell.swift file.

Any thoughts on what might be causing this issue?

Thanks!


Solution

  • I'm betting that the problem comes from :

    let topConstraint = containerView.constraints[0]
    

    A check of the constraints size can prove it easily... :)

    You forgot to call the active method on the constraints when you create them, and that does not add them to the constraint list

    i.e :

    containerView.heightAnchor.constraintEqualToConstant(100).active = true