SWIFT TableView无法加载文本

时间:2014-10-20 10:27:00

标签: objective-c uitableview swift

我以编程方式创建一个tableView。由于某种原因,表视图始终为空。请帮我找一下这个bug。这是我的代码

//设置我们需要的所有视图

func setupTableView() {
    self.tableView = UITableView(frame: CGRectMake(0, 20, 320, self.heighTableView))
    self.tableView!.tableHeaderView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, CGFloat(self.heighTableViewHeader)))
    self.tableView!.backgroundColor = UIColor.clearColor()

self.tapMapViewGesture = UITapGestureRecognizer(target: self, action: "handleTapMapView:")
        self.tapTableViewGesture = UITapGestureRecognizer(target: self, action: "handleTapTableView:")
        self.tapTableViewGesture!.delegate = self
        self.tableView!.tableHeaderView?.addGestureRecognizer(self.tapMapViewGesture!)
        self.tableView!.addGestureRecognizer(self.tapTableViewGesture!)

        // Init selt as default tableview's delegate & datasource
        //self.tableView!.dataSource = self
        self.tableView!.delegate = self
        self.view.addSubview(self.tableView!)
    }


// UITableViewDataSource Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(tableView:UITableView!, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat {

    return 80

}


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

    var identifier = "Cell"

       var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as UITableViewCell?

        cell!.textLabel!.text = "Hello World !"
   // }
 return cell!
}

1 个答案:

答案 0 :(得分:3)

试试这个:

class ViewController: UIViewController, UITableViewDelegate, MKMapViewDelegate, UIGestureRecognizerDelegate,UITableViewDataSource

然后通过命令+点击UITableViewDataSource

复制这两个函数来替换你的函数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

}

和另一个是:

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

}  

并将所有代码放入这两个函数中并再试一次,因为在你的代码中这两个函数没有被调用,但通过这样做,你的函数将被调用,你已经将所有必需的代码放入这个函数中。

并删除

中的评论

self.tableView!.dataSource = self

可能这可以帮到你。

编辑本答案:

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

    var identifier : NSString = "Cell"

    var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell

    if !(cell != nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifier)
    }
    cell?.textLabel?.text = "Hello World"
    return cell!
    }