2017-02-15 12 views
1

我有一个关于代码的顺序问题与cellForRowAt代码代码之后被称为细胞的类

执行这是我cellForRowAt功能

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! MyTableViewCell 
    print(1) 
    return cell 
} 

这是我的代码在我MyTableViewCell.swift

override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 

    print(2) 
} 

当我运行我的代码。控制台日志打印此结果

2 
1 

因此,我的单元格类中的代码在cellForRowAt中的代码之前运行。

但是,我希望我的单元格类中的代码在cellForRowAt中的代码之后运行。 我想要的结果是这样的:

1 
2 

我怎样才能做到这样呢?

回答

1

func doMyStuff() { 
    print(2) 
} 

再次回到你的cellForRowAtIndexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! MyTableViewCell 
    print(1) 
    cell.doMyStuff() 
    return cell 
} 
+0

谢谢。这就是我需要的! –

0

尝试这样做的东西不是在初始化函数,但在awakeFromNib

override func awakeFromNib(){ 
super.awakeFromNib() 
//stuff 
} 
+0

我使用tableView.dequeueReusableCell来创建tableViewCell,而不是从IB那么awakeFromNib将不会运行:( –

+0

我看你正在使用* MyTableViewCell *。那么,在这个类中,你重写awakeFromNib。当然,如果MyTableViewCell继承自TableViewCell –

+0

但我不使用IB来创建TableView。我以编程方式创建TableView,以便我必须使用init(style:reuseIdentifier)而不是使用awakeFromNib() –

0

您可以创建一个样式规格的自定义单元格类,然后当你的cellForRowAtIndexPath实例化一个细胞,你可以用你的自定义单元类。所以,这样的事情:

myCell = tableView.dequeueReusableCellWithIdentifier("topicCell") as!  topicTableViewCell 

哪里topicTableViewCell是你自己的UITableViewCell

类在增加一个功能