2015-05-14 87 views
0

我遇到了一个问题,我的应用会冻结,如果当我按下它来获取下一个场景时,它将视图控制器与tableview嵌套在其中。该应用只会在声明该表有多少行时冻结。如果有人知道如何解决这个问题,不胜感激。IOS桌面问题

class ViewController: UIViewController, UITableViewDataSource { 
    func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell = UITableViewCell() 
     cell.textLabel?.text = "hello" 
     return cell 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 
+4

你是什么意思的“应用程序将冻结”?它会崩溃吗?你有错误日志吗?或者它只是阻止用户界面? –

+0

请您在发布问题时务必清楚。 “如果我按下它”,你是什么意思?按什么?除此之外,当您指定行数时,应用程序会冻结,但您必须指定行数。否则,该应用程序应该会给你一个运行时错误。所以,我相信你不想这么做。请说明你的意思。 – Natasha

回答

2

您是否设置了表视图的dataSource?您必须在代码中调用tableView.dataSource = self地方(最可能是在viewDidLoad方法)

+0

我不认为,这是因为cellForRowAtIndexPath和numberOfRowsInSection在UITableViewDataSource下定义的问题。 – Natasha

+0

@natasha你绝对正确。我编辑了我的答案 –

0

与您的代码的问题是,在tableView(_:cellForRowAtIndexPath:)您创建的每个方法被调用时细胞。这不是表格视图(或集合视图)的工作方式。

这些组件背后的想法是重用它们的单元,以便您的应用程序显示更好的性能。如果你有1000个单元呢?您将为每个单元格创建1000个UITableViewCell对象?这是dequeueReusableCellWithIdentifier(_:)派上用场。

所以设置标识符在Interface Builder你的细胞,例如“细胞”,并得到这样的细胞:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell 

这是正确的道路要走。

0

您必须确保为表格视图单元格(在故事板或代码中)设置了正确的重用标识符。

故事板:

enter image description here

,如果你想这样做的代码,把这个viewDidLoad()

tableView.registerClass(UITableViewCell, forHeaderFooterViewReuseIdentifier: "cellIdentifier") 

重要的是知道你应该只使用一个的以上。如果你在Storyboard中定义你的UI,我推荐第一种方法。

然后,当您创建tableView(_:, cellForRowAtIndexPath)细胞,而不是这样的:

var cell = UITableViewCell() 

从重用队列使用单元格像这样:您要为单元对象

var cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) as! UITableViewCell 
0

每次,使确定你使用重用标识符。

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell