ViewController为主视图控制器,添加UITableView
如果在ViewController中实现这个UITableView的代理,能正常使用
但是如果我在另外一个类中实现UITableView的代理时,代理将不被调用,这是为什么呢?
代码如下:
//代理类
import UIKit
class TableViewDelegate:NSObject,UITableViewDelegate,UITableViewDataSource {
override init(){
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCellWithIdentifier("testCell", forIndexPath: indexPath)
var cell = tableView.dequeueReusableCellWithIdentifier("testCell")
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "testCell")
}
cell?.backgroundColor = UIColor.blueColor()
return cell!
}
}
class ViewController: UIViewController {
@IBOutlet weak var testTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let table = UITableView(frame: self.view.frame, style: .Grouped)
self.view.addSubview(table)
let delegate = TableViewDelegate()
table.dataSource = delegate
table.delegate = delegate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
原来原因很简单,因为table view的delegate和dataSource都是弱引用,而我定义的delegate使用的是局部变量,所以当viewDidLoad()方法执行完成,table view的delegate和dataSource的对象就被释放回收了,也就是说出了viewDidLoad()方法,table view的delegate和dataSource都为nil了
所以我们要将自定义的delegate常量放在适当的常量作用域内,因此我把它放在了整个类的作用域内
class ViewController: UIViewController {
@IBOutlet weak var testTable: UITableView!
let delegate = TableViewDelegate()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let table = UITableView(frame: self.view.frame, style: .Grouped)
self.view.addSubview(table)
table.dataSource = delegate
table.delegate = delegate
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}