Подтвердить что ты не робот

Участник UITableView с использованием расширений swift

Это довольно простой вопрос, который я думаю. Я разделил свой UITableView делегат/источники данных на свои собственные расширения

//MARK: - UITableView Data Source/Delegate

extension TweetsViewController: UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! TweetCell
        return cell
    }
}

Однако в самом контроллере представления мне нужно установить делегат tblView

class TweetsViewController : UIViewController {

    @IBOutlet weak var tblView: UITableView!


    var fetchedResultsController : NSFetchedResultsController!

    //MARK: View Management

    override func viewDidLoad() {
        super.viewDidLoad()

        tblView.dataSource = self


    }
}

Однако, поскольку контроллер представления не соответствует протоколам, но с ними обрабатываются расширения, как я могу явно указать источник данных и делегат для tableView? Спасибо!

4b9b3361

Ответ 1

Вы можете разделить расширение, так как вы можете проверить в разделе документацию по яблоку о процедурах обработки расширений.

Здесь я реализую минимальный код, выполняющий то, что вы просите, проверьте его.

  import UIKit


class TableViewViewController: UIViewController {
    @IBOutlet weak var table: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        table.delegate = self
        table.dataSource = self
    }
}

extension TableViewViewController: UITableViewDelegate,UITableViewDataSource {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
        cell.textLabel!.text = "it works"
        return cell
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

Ответ 2

В Swift 3 и выше изменились методы данных и методы делегирования таблицы.

import UIKit

class HomeViewController: UIViewController {

  @IBOutlet var tblPropertyList: UITableView!
  // MARK: - View Life Cycle
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tblPropertyList.delegate = self
    tblPropertyList.dataSource = self
  }

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

// MARK: - Table View DataSource
extension HomeViewController: UITableViewDataSource {

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
    cell.textLabel!.text =  "\(indexPath.row) - Its working"
    return cell
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2
  }

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

// MARK: - Table View Delegate
extension HomeViewController: UITableViewDelegate {

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow
    let currentCell = tableView.cellForRow(at: indexPath!)!
    print(currentCell.textLabel!.text!)

  }
}

Ответ 3

  контроллер представления не соответствует протоколам, но имеет расширения, обрабатывающие их

Это неверно Расширение делает контроллер представления соответствующим протоколам, а источник данных и делегат могут быть установлены как обычно, например: self.tableView.delegate = self

Ответ 4

Теперь в Swift 5.1 вам не нужно наследовать UITableViewDelegate и UITableViewDataSource

extension HomeViewController {

// MARK: - Table View DataSource

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath)
    cell.textLabel!.text =  "\(indexPath.row) - Its working"
    return cell
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2
  }

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

// MARK: - Table View Delegate

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let indexPath = tableView.indexPathForSelectedRow
    let currentCell = tableView.cellForRow(at: indexPath!)!
    print(currentCell.textLabel!.text!)

  }
}