3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftDataをUIKitで利用する

Posted at

概要

SwiftDataに関する記事でほとんどがSwiftUIで書かれていたので、
UIKitでサンプルアプリを作りました。
テキストフィールドに入力した値をテーブルビューに表示するシンプルなアプリです。

import UIKit
import SwiftData

class ViewController: UIViewController {
    var container: ModelContainer?
    var dataSource: UITableViewDiffableDataSource<Section, User>?
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        container = try? ModelContainer(for: User.self)
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "User")
        createTableViewDatasource()
        loadUsers()
    }
    
    func loadUsers() {
        let descriptor = FetchDescriptor<User>()
        let users = (try? container?.mainContext.fetch(descriptor)) ?? []

        var snapshot = NSDiffableDataSourceSnapshot<Section, User>()
        snapshot.appendSections([.users])
        snapshot.appendItems(users)
        dataSource?.apply(snapshot, animatingDifferences: false)
    }
    
    @objc func addSamples(name: String) {
        container?.mainContext.insert(User(name: name))
        loadUsers()
        textField.text = ""
    }
    
    private func createTableViewDatasource() {
        dataSource = UITableViewDiffableDataSource<Section, User>(tableView: tableView) { tableView, indexPath, user in
            let cell = tableView.dequeueReusableCell(withIdentifier: "User", for: indexPath)
            var content = cell.defaultContentConfiguration()
            content.text = "\(user.name)"
            cell.contentConfiguration = content
            return cell
        }
    }
    
    @IBAction func addButtonDidTap(_ sender: UIButton) {
        if let name = textField.text {
            addSamples(name: name)
        }
    }
}

extension ViewController: UITableViewDelegate {
    
}

@Model
class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

enum Section {
    case users
}

simulator_screenshot_B694886B-E656-462D-B3AF-62972C668EC6.png

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?