使用Swift语言使用自定义UITableViewCell填充UITableView

时间:2014-06-30 18:57:06

标签: swift

我在Objective-C中已经完成了这么多次,但由于某种原因,Swift没有按预期工作。以下代码不会在一行中填充UITableView单元格:

 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        var cell =  tableView.dequeueReusableCellWithIdentifier("BudgetTableViewCell", forIndexPath: indexPath) as BudgetTableViewCell

        cell.budgetTitle.text = "My Budget" 

        return cell
    }

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1;
    }


    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return 1;
    }

我确保在Storyboard中正确连接budgetLabel。调用所有上述方法,但是当加载UITableView时,没有显示任何内容。

Apple提供的UITableViewController模板:

 // #pragma mark - Table view data source

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

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


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

        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

        // Configure the cell...

        return cell
    }

1 个答案:

答案 0 :(得分:1)

UITableView委托方法的接口规范与覆盖尝试略有不同。以下是Apple Xcode模板代码作为实现者的起点(对于Master / Detail项目)提供的界面:

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {}

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {}

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

您的代码在许多地方使用?!。这意味着没有覆盖匹配;相反,你正在创建新类型的方法。因此,您的方法永远不会被调用。

注意:Master / Detail项目的Apple Xcode模板,作为UITableViewController子类的Cocoa Touch类,以及UITableViewDataSource文档都使用不一致的签名UITableViewUITableView?和{{ 1}}使用。

但是,应该清楚的是,在委托方法中,UITableView!的声明应该是适当的,因为如果委托甚至被调用,则提供的表参数将存在(不是UITableView!)。 / p>

相关问题