Help us understand the problem. What is going on with this article?

[Swifty]データソースを分割する

More than 3 years have passed since last update.

そもそもUITableViewはUITableViewDataSourceプロトコルとUITableViewDelegateプロトコルの二つのプロトコルを利用するということから、複数のクラスで更生できる物だが、見通しが良く、記述が楽ということから、ベースとなるビューコントローラで実装されている場合が多いと思う。

今回のデータソースに分割するお話は、クラス構成から素直に実装とも言えると思う。

まずは、データソースを切り離してみる。

class DataSource: NSObject, UITableViewDataSource {
    private var document = Document.sharedInstance
 
    func addItemTo(tableView: UITableView) {
        if document.numberOfCards < 5 {
            document.addNewCard(at: 0)
            insertTopRowIn(tableView: tableView)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return document.numberOfCards
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CardCell
        let card = document.getCard(at: indexPath.row)
        cell.fillWith(card: card)
        return cell
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            document.deleteCard(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
        }
    }
    
    func insertTopRowIn(tableView: UITableView) {
        let indexPath = IndexPath(row: 0, section: 0)
        tableView.insertRows(at: [indexPath], with: .fade)
    }
    
    func deleteRowAtIndexPath(indexPath: NSIndexPath, from tableView: UITableView) {
    }
}
class MasterViewController: UITableViewController {
 
    private var dataSource = DataSource()
    var detailViewController: DetailViewController? = nil
 
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView.dataSource = dataSource
        self.navigationItem.leftBarButtonItem = self.editButtonItem
 
        let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.addNewCard(sender:)))
        self.navigationItem.rightBarButtonItem = addButton
        if let split = self.splitViewController {
            let controllers = split.viewControllers
            self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
        }
    }
 
    override func viewWillAppear(_ animated: Bool) {
        self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed
        super.viewWillAppear(animated)
    }
 
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
    @IBAction private func addNewCard(sender: UIBarButtonItem) {
        dataSource.addItemTo(tableView: tableView)
    }
 
    // MARK: - Segues
 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow {
                let card = Document.sharedInstance.getCard(at: indexPath.row)
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                controller.detailItem = card
                controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }
 
    // MARK: - Table View
 
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
 
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
}

ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/Hand - GitHub

関連情報
文化を調和させる

【Cocoa練習帳】
http://www.bitz.co.jp/weblog/

http://ameblo.jp/bitz/(ミラー・サイト)

m_yukio
UNIX系ソフトハウスと組み込みシステムのベンチャーを経て2001年に独立。 プラットフォームを限定せずに何にでも挑戦してきましたが、最近はiOSアプリ開発に注力しています。
http://www.bitz.co.jp/weblog/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした