Skip to content

Instantly share code, notes, and snippets.

@yzhong52
Created February 16, 2020 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzhong52/f50705eee46a87d18b105c8700a3de8f to your computer and use it in GitHub Desktop.
Save yzhong52/f50705eee46a87d18b105c8700a3de8f to your computer and use it in GitHub Desktop.
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