UITableView in Swift

前端 未结 17 1419
滥情空心
滥情空心 2020-12-04 08:09

I\'m struggling to figure out what\'s wrong with this code snippet. This is currently working in Objective-C, but in Swift this just crashes on the first line of the method.

17条回答
  •  被撕碎了的回忆
    2020-12-04 08:42

    Also see matt's answer which contains the second half of the solution

    Let's find a solution without creating custom subclasses or nibs

    The real problem is in the fact that Swift distinguishes between objects that can be empty (nil) and objects that can't be empty. If you don't register a nib for your identifier, then dequeueReusableCellWithIdentifier can return nil.

    That means we have to declare the variable as optional:

    var cell : UITableViewCell?
    

    and we have to cast using as? not as

    //variable type is inferred
    var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
    
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
    }
    
    // we know that cell is not empty now so we use ! to force unwrapping but you could also define cell as
    // let cell = (tableView.dequeue... as? UITableViewCell) ?? UITableViewCell(style: ...)
    
    cell!.textLabel.text = "Baking Soda"
    cell!.detailTextLabel.text = "1/2 cup"
    
    cell!.textLabel.text = "Hello World"
    
    return cell
    

提交回复
热议问题