在swift中只生成一个简单的Tableview,Tableview根本不填充任何内容。正在填充图像。

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

    let cellIdentifier = "cellIdentifier";
    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell;

    if !(cell != nil){
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
            reuseIdentifier: cellIdentifier)

    }

    if(indexPath.row==0){
        cell!.textLabel.text = "POG Validation"
        cell!.imageView.image =  UIImage(named: "myImg")
    }

return cell;

cell!.textLabel的帧为(0,0,0,0)。没有数据被填充。
(lldb) po cell!.textLabel;

<UITableViewLabel: 0x7ce6c510; frame = (0 0; 0 0); userInteractionEnabled =  NO; layer = <_UILabelLayer: 0x7ce6c5d0>>

最佳答案

一旦我修复了您的编译错误,您的代码就可以正常工作了:

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

    let cellIdentifier = "cellIdentifier";
    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell;

    if !(cell != nil){
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
            reuseIdentifier: cellIdentifier)

    }

    if(indexPath.row==0){
        // your forgot the '?'s
        cell!.textLabel?.text = "POG Validation"
        cell!.imageView?.image =  UIImage(named: "myImg")
    }

    return cell!; // you forgot the '!'
}

我会这样写的:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "cellIdentifier";
    let dequedCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
    let cell = dequedCell ?? UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier) as UITableViewCell

    if(indexPath.row==0){
        cell.textLabel?.text = "POG Validation"
        cell.imageView?.image = UIImage(named: "myImg")
    }

    return cell;
}

关于uitableview - Swift TableView数据填充,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28245332/

10-12 00:18
查看更多