Таблицы в Swift

НАВИГАЦИЯ ПО СТРАНИЦЕ

UITableView UICollectionView

В разработке приложений на Swift с использованием UIKit, таблицы и коллекции играют важную роль для отображения и взаимодействия с данными. В основе этого лежат классы UITableView и UICollectionView.

UITableView:

  1. DataSource и Delegate:

    • UITableViewDataSource предоставляет данные для таблицы.

    • UITableViewDelegate обрабатывает события, такие как выбор ячейки.

  2. Регистрация ячеек:

    • Ячейки должны быть зарегистрированы перед использованием.

    • Для использования стандартных ячеек:

      tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")
  3. DataSource методы:

    • numberOfSections(in:) - количество секций.

    • tableView(_:numberOfRowsInSection:) - количество строк в секции.

    • tableView(_:cellForRowAt:) - настройка и возврат ячейки.

      extension ViewController: UITableViewDataSource {
          func numberOfSections(in tableView: UITableView) -> Int {
              return 1
          }
      
          func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
              return data.count
          }
      
          func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
              let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath)
              cell.textLabel?.text = data[indexPath.row]
              return cell
          }
      }
  4. Delegate методы:

    • tableView(_:didSelectRowAt:) - вызывается при выборе ячейки.

    • Для обработки действий с ячейками можно использовать didDeselectRowAt, willDisplay, и другие методы.

      extension ViewController: UITableViewDelegate {
          func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
              print("Выбрана ячейка с индексом \(indexPath.row)")
          }
      }

UICollectionView:

  1. DataSource и Delegate:

    • UICollectionViewDataSource предоставляет данные для коллекции.

    • UICollectionViewDelegate обрабатывает события, такие как выбор ячейки.

  2. Регистрация ячеек:

    • Аналогично UITableView, ячейки должны быть зарегистрированы перед использованием.

      collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CellIdentifier")
  3. Layout:

    • UICollectionViewFlowLayout определяет расположение и размер ячеек.

    • Для настройки layout используйте методы sizeForItemAt, minimumLineSpacing, minimumInteritemSpacing и др.

      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
          return CGSize(width: 100, height: 100)
      }
  4. DataSource методы:

    • numberOfSections(in:) - количество секций.

    • collectionView(_:numberOfItemsInSection:) - количество ячеек в секции.

    • collectionView(_:cellForItemAt:) - настройка и возврат ячейки.

      extension ViewController: UICollectionViewDataSource {
          func numberOfSections(in collectionView: UICollectionView) -> Int {
              return 1
          }
      
          func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
              return data.count
          }
      
          func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
              let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellIdentifier", for: indexPath)
              cell.backgroundColor = UIColor.blue
              return cell
          }
      }
  5. Delegate методы:

    • collectionView(_:didSelectItemAt:) - вызывается при выборе ячейки.

    • Аналогично UITableView, используйте didDeselectItemAt, willDisplay, и другие методы для обработки действий.

      extension ViewController: UICollectionViewDelegate {
          func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
              print("Выбрана ячейка с индексом \(indexPath.item)")
          }
      }

Работа с таблицами и коллекциями в Swift с использованием UIKit предоставляет множество возможностей для отображения и взаимодействия с данными. Пользуйтесь UITableView и UICollectionView в зависимости от требований вашего приложения.