2017-08-28 7 views
0

UITableView.dataSourceは拡張機能で正常に動作しますが、デリゲートでは機能しません。 私は新しいプロジェクトを作成し、ストーリーボードに1つだけUITableViewを追加しました。ここでSwift - デリゲートでUITableViewが機能しない

は、拡張子を使用してコードです:

デリゲートを使用して
import UIKit 

class ViewController: UIViewController { 
    @IBOutlet weak var tableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.dataSource = self 
//  tableView.dataSource = Delegate() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
} 

extension ViewController: UITableViewDataSource { 
//class Delegate: NSObject, UITableViewDataSource { 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     print(1) // called several times 
     return 1 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     print(2) // called 

     var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") 
     if cell == nil { 
      cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell") 
     } 
     return cell! 
    } 
} 

import UIKit 

class ViewController: UIViewController { 
    @IBOutlet weak var tableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
//  tableView.dataSource = self 
     tableView.dataSource = Delegate() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
} 

//extension ViewController: UITableViewDataSource { 
class Delegate: NSObject, UITableViewDataSource { 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     print(1) // called several times 
     return 1 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     print(2) // doesn't called 

     var cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") 
     if cell == nil { 
      cell = UITableViewCell(style: .default, reuseIdentifier: "UITableViewCell") 
     } 
     return cell! 
    } 
} 

誰もがこのような問題が発生していますか?

+0

あなたの '' CellForRowAt'は呼び出されませんか?テーブルビューの高さを確認してください –

+0

numberOfRowsInSectionが呼び出されたか、あなたが何度も呼び出されました//と言いました。 –

+0

@MikeAlter答えは既に下に与えられています –

答えて

2

コントローラを表示するにはDelegateオブジェクトを格納する必要があります。その理由は、UITableViewの変数dataSourceweakの変数(保持サイクルを防ぐため)であることです。つまり、変数strongのどこかに格納されていなければ、すぐに割り当てが解除されます。ここで

tableView.dataSource = Delegate() 

あなたは弱い変数と他のどこにDelegateの新しいインスタンスを割り当てます。この

class ViewController: UIViewController { 
    var delegate = Delegate() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.dataSource = self.delegate 
} 
+0

今、とても愚かな気分です。ありがとうございました。 –

1

dataSourcedelegateは両方weakあるような何かを行います。そのため、強い参照がないDelegate()オブジェクトは、viewDidLoad()以降にリリースされます。

このように委任を使用する場合は、ViewControllervar delegate: Delegate!と入力してください。その後、viewDidLoad()

self.delegate = Delegate() 
tableView.delegate = self.delegate 
関連する問題