Skip to content

Instantly share code, notes, and snippets.

@uruly
Created July 26, 2020 15:01
Show Gist options
  • Save uruly/d6cc1a7dd99d8b7881e37c6a8431b07b to your computer and use it in GitHub Desktop.
Save uruly/d6cc1a7dd99d8b7881e37c6a8431b07b to your computer and use it in GitHub Desktop.
//
// TableViewController.swift
// MultipleCollectionView
//
// Created by Reo on 2019/11/08.
// Copyright © 2019 uruly.xyz. All rights reserved.
//
// I partially copied the following code.
// https://qiita.com/abouch/items/aca979b71ad792478687
import UIKit
struct Article: Codable {
var title: String
var user: User
struct User: Codable {
var id: String
}
}
struct Qiita {
static func fetchArticle(completion: @escaping ([Article]) -> Swift.Void) {
let url = "https://qiita.com/api/v2/items"
guard var urlComponents = URLComponents(string: url) else {
return
}
urlComponents.queryItems = [
URLQueryItem(name: "per_page", value: "50"),
]
let task = URLSession.shared.dataTask(with: urlComponents.url!) { data, response, error in
guard let jsonData = data else {
return
}
do {
let articles = try JSONDecoder().decode([Article].self, from: jsonData)
completion(articles)
} catch {
print(error.localizedDescription)
}
}
task.resume()
}
}
final class TableViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView! {
didSet {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
}
}
@IBOutlet weak var tableViewConstraintHeight: NSLayoutConstraint!
private let reuseIdentifier = "cell"
private var articles: [Article] = []
override func viewDidLoad() {
super.viewDidLoad()
Qiita.fetchArticle(completion: { [weak self] (articles) in
self?.articles = articles
DispatchQueue.main.async {
self?.tableView.reloadData()
// リロード後に高さを再設定してあげる!
self?.updateTableViewHeight()
}
})
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateTableViewHeight()
}
private func updateTableViewHeight() {
// Set tableView height to content size height.
tableView.layoutIfNeeded()
tableViewConstraintHeight.constant = tableView.contentSize.height
view.layoutIfNeeded()
view.frame.size.height = tableView.contentSize.height
}
}
// MARK: - TableViewDelegate
extension TableViewController: UITableViewDelegate {}
// MARK: - UITableViewDataSource
extension TableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = articles[indexPath.row].title
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment