Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Building a Client App From Scratch - ViewController NewsManager
class ViewController: UIViewController {
private let manager = NewsManager()
private let disposeBag = DisposeBag()
private var articles: [Article] = []
private let titleLabel: UILabel = {
let label = UILabel()
label.text = NSLocalizedString("News", comment: "")
return label
}()
private let subtitleLabel: UILabel = {
let label = UILabel()
label.textColor = .gray
label.font = UIFont.systemFont(ofSize: 9)
return label
}()
private let tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.tableFooterView = UIView()
tableView.register(NewsTableViewCell.self, forCellReuseIdentifier: NewsTableViewCell.reuseIdentifier)
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 134
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
])
tableView.delegate = self
tableView.dataSource = self
let titleView = UIStackView(arrangedSubviews: [titleLabel, subtitleLabel])
titleView.axis = .vertical
titleView.alignment = .center
navigationItem.titleView = titleView
manager.news().drive(onNext: { [weak self] (state) in
self?.updateView(state: state)
}).disposed(by: disposeBag)
}
private func updateView(state: NewsManager.NewsLoadState) {
switch state {
case .loading:
subtitleLabel.text = NSLocalizedString("Loading...", comment: "")
case .updating:
subtitleLabel.text = NSLocalizedString("Updating...", comment: "")
case .loaded(let response):
articles = response.articles
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd YYYY HH:mm"
let labelFormat = NSLocalizedString("%@ Updated", comment: "")
subtitleLabel.text = String.localizedStringWithFormat(
labelFormat, dateFormatter.string(from: Date()))
tableView.reloadData()
case let .failed(error):
print("[Error] failed to load news \(error)")
subtitleLabel.text = NSLocalizedString("Update Failed", comment: "")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.