Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Section {
- var isCollaped: Bool
- let category: Category
- }
- class SourcesViewController: UIViewController {
- // MARK: - Variables and Constants
- fileprivate let defaults = UserDefaults.standard
- let realm = try! Realm()
- lazy var categories: Results<Category> = {
- self.realm.objects(Category.self)
- }()
- fileprivate var sections: [Section] = []
- // Views
- fileprivate lazy var titleView: UILabel = {
- let label = UILabel()
- label.text = "Sources"
- label.font = UIFont.boldSystemFont(ofSize: 48)
- label.layer.zPosition = 10
- return label
- }()
- fileprivate var waterView: YXWaveView?
- fileprivate let searchBar = SearchBar()
- fileprivate let addButton = UIButton(type: .custom)
- fileprivate var tableView: UITableView?
- fileprivate var createSourceLauncher: CreateSourceLauncher?
- fileprivate var prefersDarkMode: Bool {
- return UserDefaults.standard.bool(forKey: Keys.prefersDarkMode)
- }
- fileprivate var color: UIColor {
- return UIColor.getColor()
- }
- override var preferredStatusBarStyle: UIStatusBarStyle {
- return UserDefaults.standard.bool(forKey: Keys.prefersDarkMode) ? .lightContent : .default
- }
- // MARK: - Lifecycle Functions
- override func viewDidLoad() {
- super.viewDidLoad()
- self.navigationController?.isNavigationBarHidden = true
- loadCategories()
- createTableView()
- }
- override func viewSafeAreaInsetsDidChange() {
- setupWaveView()
- setupTableView()
- setupTitle()
- setupAddButton()
- }
- override func viewWillAppear(_ animated: Bool) {
- waterView?.start()
- }
- override func viewDidAppear(_ animated: Bool) {
- setColor()
- setStyle()
- }
- /*
- Removed setup functions for readability
- */
- // MARK: - Model
- private func loadCategories() {
- categories = realm.objects(Category.self)
- fillSections()
- }
- private func fillSections() {
- sections = []
- for category in categories {
- sections.append(Section(isCollaped: false, category: category))
- }
- }
- private func deleteSource(indexPath: IndexPath) {
- let confirmationController = UIAlertController(title: "Confirm", message: "", preferredStyle: .alert)
- let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
- let delete = UIAlertAction(title: "Delete", style: .destructive) { (action) in
- let source = self.categories[indexPath.section].items[indexPath.row]
- do {
- try self.realm.write {
- self.realm.delete(source)
- }
- } catch {
- print("Error deleting category, \(error)")
- }
- }
- confirmationController.addAction(cancel)
- confirmationController.addAction(delete)
- self.present(confirmationController, animated: true) {
- self.tableView?.reloadData()
- }
- }
- private func createCategory() {
- guard categories.count == 0 else {
- return
- }
- do {
- try realm.write() {
- let defaultCategories = ["Coffee", "Supplements", "Tea"]
- for category in defaultCategories {
- let newCategory = Category()
- newCategory.name = category
- realm.add(newCategory)
- }
- }
- } catch {
- print("Error creating Category, \(error)")
- }
- fillSections()
- tableView?.reloadData()
- }
- private func createSource() {
- let selectedCategory = categories[1]
- do {
- try realm.write() {
- let newSource = Source()
- newSource.name = "Starbucks Coffee"
- newSource.caffeineContent = 180
- selectedCategory.items.append(newSource)
- }
- } catch {
- print("Error creating source, \(error)")
- }
- fillSections()
- tableView?.reloadData()
- }
- // MARK: - Styling
- fileprivate func setStyle() {
- let styleColor = UIColor.getStyleColor()
- let maskingColor = UIColor.getMaskingColor()
- waterView?.realWaveColor = styleColor
- waterView?.maskWaveColor = maskingColor
- view.backgroundColor = styleColor
- tableView?.backgroundColor = styleColor
- titleView.textColor = UIColor.getTextColor()
- addButton.tintColor = UIColor.getTextColor()
- setNeedsStatusBarAppearanceUpdate()
- }
- fileprivate func setColor() {
- waterView?.backgroundColor = UIColor.getColor()
- }
- // MARK: - Present other views
- @objc private func showCreateSourceLauncher() {
- createSourceLauncher = CreateSourceLauncher()
- createSourceLauncher!.sourceDelegate = self
- createSourceLauncher!.setup()
- createSourceLauncher!.setStyle()
- createSourceLauncher!.showCollectionView(height: 100 + view.safeAreaInsets.bottom)
- }
- public func deallocateLauncher(type: LauncherType) {
- createSourceLauncher = nil
- }
- // Show View Controller for creating a new source
- public func showCreateSourceController() {
- createSource()
- return
- let addSourceVC = AddSourceViewController()
- if #available(iOS 13.0, *) {
- addSourceVC.modalPresentationStyle = .popover
- }
- self.present(addSourceVC, animated: true, completion: nil)
- }
- // Show View Controller for creating a new category
- public func showCreateCategoryController() {
- createCategory()
- return
- let addCategoryController = AddCategoryViewController()
- if #available(iOS 13.0, *) {
- addCategoryController.modalPresentationStyle = .popover
- }
- self.present(addCategoryController, animated: true, completion: nil)
- }
- public func showSourceViewController() {
- let sourceVC = SourceViewController()
- self.navigationController?.pushViewController(sourceVC, animated: true)
- }
- }
- // MARK: - Search Bar Methods
- extension SourcesViewController: UISearchBarDelegate {
- func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
- // Filter results
- // Update table view
- }
- func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
- }
- func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
- searchBar.endEditing(true)
- searchBar.resignFirstResponder()
- }
- }
- // MARK: - Table View Methods
- extension SourcesViewController: UITableViewDelegate, UITableViewDataSource, SwipeTableViewCellDelegate {
- func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
- guard orientation == .right else { return nil }
- let deleteAction = SwipeAction(style: .destructive, title: nil) { action, indexPath in
- self.deleteSource(indexPath: indexPath)
- }
- let deleteImage = UIImage(named: Assets.trashIcon)?.withRenderingMode(.alwaysTemplate)
- deleteAction.image = deleteImage?.withTintColor(UIColor.getTextColor())
- return [deleteAction]
- }
- func numberOfSections(in tableView: UITableView) -> Int {
- return categories.count
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- if sections[section].isCollaped {
- return 0
- }
- return categories[section].items.count
- }
- func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
- let headerFrame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 40)
- let headerSection = sections[section]
- let headerButton = SectionTableViewHeader(frame: headerFrame, title: headerSection.category.name, isCollapsed: headerSection.isCollaped)
- headerButton.addTarget(self, action: #selector(handleExpandHeader), for: .touchUpInside)
- headerButton.setStyle()
- headerButton.tag = section
- return headerButton
- }
- @objc func handleExpandHeader(sender: SectionTableViewHeader) {
- let isCollapsed = sections[sender.tag].isCollaped
- sections[sender.tag].isCollaped = !isCollapsed
- var indexPaths: [IndexPath] = []
- for (index, _) in categories[sender.tag].items.enumerated() {
- indexPaths.append(IndexPath(row: index, section: sender.tag))
- }
- print(indexPaths.count)
- if isCollapsed {
- tableView?.insertRows(at: indexPaths, with: .fade)
- } else {
- tableView?.deleteRows(at: indexPaths, with: .fade)
- }
- var rotationAngle: CGFloat = CGFloat.pi / 2
- if !isCollapsed {
- rotationAngle = -rotationAngle
- }
- sender.rotateImage(angle: rotationAngle)
- }
- func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
- return 40
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.sourceCellId, for: indexPath) as! CustomizableTableViewCell
- cell.delegate = self
- let category = sections[indexPath.section].category
- let item = category.items[indexPath.row]
- cell.titleText = item.name
- cell.primaryIconName = item.imageString
- return cell
- }
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- return 48
- }
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- tableView.deselectRow(at: indexPath, animated: true)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement