Creating static cells in Swift

I am trying to create static cells in UITableViewCell

. I started by adding 2 cells in Interface Builder and gave them an id title

and news

. Then I created an array with these two IDs and added it to cellForRowAtIndexPath

. However, I keep getting the following error:

'unable to dequeue a cell with identifier title - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

      

Array

var menuItems = ["title", "news"]

      

tableView

delegation methods

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 2
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 64
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier(menuItems[indexPath.row], forIndexPath: indexPath) as! UITableViewCell

    cell.backgroundColor = UIColor(white: 0.2, alpha: 1.0)

    var bottomView: UIView = UIView(frame: CGRectMake(0, cell.frame.height-1, cell.frame.width, 1))
    bottomView.backgroundColor = UIColor(white: 0.2, alpha: 0.15)
    cell.contentView.addSubview(bottomView)

    return cell
}

      

+3


source to share


2 answers


It seems you need to register the class UITableViewCell

manually for the cell. You can achieve this by calling

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: menuItems[indexPath.row])

      



in your function viewDidLoad()

functioncellForRowAtIndexPath

UITableViewDataSource

+2


source


As with the error message, you must register them if you created them as an empty UI file. This can be simply put in the viewDidLoad function.



override func viewDidLoad() {
        super.viewDidLoad()

        var nib = UINib(nibName: "OrangeCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "oranges")

        var nib2 = UINib(nibName: "AppleCell", bundle: nil)
        tableView.registerNib(nib2, forCellReuseIdentifier: "apples")
}

      

0


source







All Articles