Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 11.10 KB | None | 0 0
  1. struct Section {
  2.     var isCollaped: Bool
  3.     let category: Category
  4. }
  5.  
  6.  
  7. class SourcesViewController: UIViewController {
  8.    
  9.    
  10.     // MARK: - Variables and Constants
  11.    
  12.    
  13.     fileprivate let defaults = UserDefaults.standard
  14.     let realm = try! Realm()
  15.    
  16.    
  17.     lazy var categories: Results<Category> = {
  18.         self.realm.objects(Category.self)
  19.     }()
  20.    
  21.     fileprivate var sections: [Section] = []
  22.    
  23.    
  24.     // Views
  25.     fileprivate lazy var titleView: UILabel = {
  26.        
  27.         let label = UILabel()
  28.        
  29.         label.text = "Sources"
  30.         label.font = UIFont.boldSystemFont(ofSize: 48)
  31.         label.layer.zPosition = 10
  32.        
  33.         return label
  34.     }()
  35.    
  36.     fileprivate var waterView: YXWaveView?
  37.     fileprivate let searchBar = SearchBar()
  38.     fileprivate let addButton = UIButton(type: .custom)
  39.     fileprivate var tableView: UITableView?
  40.     fileprivate var createSourceLauncher: CreateSourceLauncher?
  41.    
  42.    
  43.     fileprivate var prefersDarkMode: Bool {
  44.         return UserDefaults.standard.bool(forKey: Keys.prefersDarkMode)
  45.     }
  46.    
  47.    
  48.     fileprivate var color: UIColor {
  49.         return UIColor.getColor()
  50.     }
  51.    
  52.    
  53.     override var preferredStatusBarStyle: UIStatusBarStyle {
  54.         return UserDefaults.standard.bool(forKey: Keys.prefersDarkMode) ? .lightContent : .default
  55.     }
  56.    
  57.    
  58.    
  59.    
  60.     // MARK: - Lifecycle Functions
  61.    
  62.    
  63.     override func viewDidLoad() {
  64.        
  65.         super.viewDidLoad()
  66.         self.navigationController?.isNavigationBarHidden = true
  67.        
  68.         loadCategories()
  69.         createTableView()
  70.        
  71.     }
  72.    
  73.    
  74.     override func viewSafeAreaInsetsDidChange() {
  75.         setupWaveView()
  76.         setupTableView()
  77.         setupTitle()
  78.         setupAddButton()
  79.     }
  80.    
  81.    
  82.     override func viewWillAppear(_ animated: Bool) {
  83.         waterView?.start()
  84.     }
  85.    
  86.    
  87.     override func viewDidAppear(_ animated: Bool) {
  88.         setColor()
  89.         setStyle()
  90.     }
  91.  
  92.     /*
  93.         Removed setup functions for readability
  94.     */
  95.    
  96.    
  97.     // MARK: - Model
  98.    
  99.    
  100.     private func loadCategories() {
  101.         categories = realm.objects(Category.self)
  102.         fillSections()
  103.     }
  104.    
  105.    
  106.     private func fillSections() {
  107.         sections = []
  108.         for category in categories {
  109.             sections.append(Section(isCollaped: false, category: category))
  110.         }
  111.     }
  112.    
  113.    
  114.     private func deleteSource(indexPath: IndexPath) {
  115.        
  116.         let confirmationController = UIAlertController(title: "Confirm", message: "", preferredStyle: .alert)
  117.        
  118.         let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
  119.         let delete = UIAlertAction(title: "Delete", style: .destructive) { (action) in
  120.            
  121.             let source = self.categories[indexPath.section].items[indexPath.row]
  122.             do {
  123.                 try self.realm.write {
  124.                     self.realm.delete(source)
  125.                 }
  126.             } catch {
  127.                 print("Error deleting category, \(error)")
  128.             }
  129.            
  130.         }
  131.        
  132.         confirmationController.addAction(cancel)
  133.         confirmationController.addAction(delete)
  134.        
  135.         self.present(confirmationController, animated: true) {
  136.             self.tableView?.reloadData()
  137.         }
  138.     }
  139.    
  140.    
  141.     private func createCategory() {
  142.        
  143.         guard categories.count == 0 else {
  144.             return
  145.         }
  146.        
  147.         do {
  148.             try realm.write() {
  149.                
  150.                 let defaultCategories = ["Coffee", "Supplements", "Tea"]
  151.                
  152.                 for category in defaultCategories {
  153.                     let newCategory = Category()
  154.                     newCategory.name = category
  155.                    
  156.                     realm.add(newCategory)
  157.                 }
  158.                
  159.             }
  160.         } catch {
  161.             print("Error creating Category, \(error)")
  162.         }
  163.        
  164.         fillSections()
  165.         tableView?.reloadData()
  166.     }
  167.    
  168.    
  169.     private func createSource() {
  170.        
  171.         let selectedCategory = categories[1]
  172.        
  173.         do {
  174.             try realm.write() {
  175.                
  176.                 let newSource = Source()
  177.                 newSource.name = "Starbucks Coffee"
  178.                 newSource.caffeineContent = 180
  179.                
  180.                 selectedCategory.items.append(newSource)
  181.                
  182.             }
  183.         } catch {
  184.             print("Error creating source, \(error)")
  185.         }
  186.        
  187.         fillSections()
  188.         tableView?.reloadData()
  189.        
  190.     }
  191.    
  192.    
  193.    
  194.    
  195.     // MARK: - Styling
  196.    
  197.    
  198.     fileprivate func setStyle() {
  199.        
  200.         let styleColor = UIColor.getStyleColor()
  201.         let maskingColor = UIColor.getMaskingColor()
  202.        
  203.         waterView?.realWaveColor = styleColor
  204.         waterView?.maskWaveColor = maskingColor
  205.        
  206.         view.backgroundColor = styleColor
  207.         tableView?.backgroundColor = styleColor
  208.        
  209.         titleView.textColor = UIColor.getTextColor()
  210.         addButton.tintColor = UIColor.getTextColor()
  211.        
  212.         setNeedsStatusBarAppearanceUpdate()
  213.     }
  214.    
  215.    
  216.     fileprivate func setColor() {
  217.         waterView?.backgroundColor = UIColor.getColor()
  218.     }
  219.    
  220.    
  221.    
  222.    
  223.     // MARK: - Present other views
  224.    
  225.    
  226.     @objc private func showCreateSourceLauncher() {
  227.        
  228.         createSourceLauncher = CreateSourceLauncher()
  229.        
  230.         createSourceLauncher!.sourceDelegate = self
  231.         createSourceLauncher!.setup()
  232.         createSourceLauncher!.setStyle()
  233.         createSourceLauncher!.showCollectionView(height: 100 + view.safeAreaInsets.bottom)
  234.        
  235.     }
  236.    
  237.     public func deallocateLauncher(type: LauncherType) {
  238.         createSourceLauncher = nil
  239.     }
  240.    
  241.    
  242.     // Show View Controller for creating a new source
  243.     public func showCreateSourceController() {
  244.  
  245.         createSource()
  246.         return
  247.        
  248.         let addSourceVC = AddSourceViewController()
  249.        
  250.         if #available(iOS 13.0, *) {
  251.             addSourceVC.modalPresentationStyle = .popover
  252.         }
  253.  
  254.         self.present(addSourceVC, animated: true, completion: nil)
  255.     }
  256.    
  257.    
  258.     // Show View Controller for creating a new category
  259.     public func showCreateCategoryController() {
  260.        
  261.         createCategory()
  262.         return
  263.        
  264.         let addCategoryController = AddCategoryViewController()
  265.        
  266.         if #available(iOS 13.0, *) {
  267.             addCategoryController.modalPresentationStyle = .popover
  268.         }
  269.        
  270.         self.present(addCategoryController, animated: true, completion: nil)
  271.     }
  272.    
  273.    
  274.     public func showSourceViewController() {
  275.         let sourceVC = SourceViewController()
  276.         self.navigationController?.pushViewController(sourceVC, animated: true)
  277.     }
  278.  
  279. }
  280.  
  281.  
  282.  
  283.  
  284. // MARK: - Search Bar Methods
  285.  
  286.  
  287. extension SourcesViewController: UISearchBarDelegate {
  288.    
  289.    
  290.     func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  291.         // Filter results
  292.        
  293.         // Update table view
  294.     }
  295.    
  296.    
  297.     func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
  298.        
  299.     }
  300.    
  301.    
  302.     func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  303.         searchBar.endEditing(true)
  304.         searchBar.resignFirstResponder()
  305.     }
  306.    
  307.    
  308. }
  309.  
  310.  
  311.  
  312.  
  313. // MARK: - Table View Methods
  314.  
  315.  
  316. extension SourcesViewController: UITableViewDelegate, UITableViewDataSource, SwipeTableViewCellDelegate {
  317.    
  318.    
  319.     func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
  320.        
  321.         guard orientation == .right else { return nil }
  322.        
  323.         let deleteAction = SwipeAction(style: .destructive, title: nil) { action, indexPath in
  324.             self.deleteSource(indexPath: indexPath)
  325.         }
  326.        
  327.         let deleteImage = UIImage(named: Assets.trashIcon)?.withRenderingMode(.alwaysTemplate)
  328.         deleteAction.image = deleteImage?.withTintColor(UIColor.getTextColor())
  329.         return [deleteAction]
  330.     }
  331.    
  332.    
  333.     func numberOfSections(in tableView: UITableView) -> Int {
  334.         return categories.count
  335.     }
  336.    
  337.    
  338.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  339.        
  340.         if sections[section].isCollaped {
  341.             return 0
  342.         }
  343.        
  344.         return categories[section].items.count
  345.     }
  346.    
  347.    
  348.     func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  349.        
  350.         let headerFrame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 40)
  351.        
  352.         let headerSection = sections[section]
  353.        
  354.         let headerButton = SectionTableViewHeader(frame: headerFrame, title: headerSection.category.name, isCollapsed: headerSection.isCollaped)
  355.         headerButton.addTarget(self, action: #selector(handleExpandHeader), for: .touchUpInside)
  356.         headerButton.setStyle()
  357.         headerButton.tag = section
  358.        
  359.         return headerButton
  360.     }
  361.    
  362.    
  363.    
  364.     @objc func handleExpandHeader(sender: SectionTableViewHeader) {
  365.        
  366.         let isCollapsed = sections[sender.tag].isCollaped
  367.         sections[sender.tag].isCollaped = !isCollapsed
  368.        
  369.         var indexPaths: [IndexPath] = []
  370.         for (index, _) in categories[sender.tag].items.enumerated() {
  371.             indexPaths.append(IndexPath(row: index, section: sender.tag))
  372.         }
  373.        
  374.         print(indexPaths.count)
  375.        
  376.         if isCollapsed {
  377.             tableView?.insertRows(at: indexPaths, with: .fade)
  378.         } else {
  379.             tableView?.deleteRows(at: indexPaths, with: .fade)
  380.         }
  381.        
  382.         var rotationAngle: CGFloat = CGFloat.pi / 2
  383.         if !isCollapsed {
  384.             rotationAngle = -rotationAngle
  385.         }
  386.        
  387.         sender.rotateImage(angle: rotationAngle)
  388.        
  389.     }
  390.    
  391.    
  392.    
  393.     func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  394.         return 40
  395.     }
  396.    
  397.    
  398.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  399.        
  400.         let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifiers.sourceCellId, for: indexPath) as! CustomizableTableViewCell
  401.        
  402.         cell.delegate = self
  403.        
  404.         let category = sections[indexPath.section].category
  405.         let item = category.items[indexPath.row]
  406.        
  407.         cell.titleText = item.name
  408.         cell.primaryIconName = item.imageString
  409.        
  410.         return cell
  411.     }
  412.    
  413.     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  414.         return 48
  415.     }
  416.    
  417.    
  418.     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  419.        
  420.         tableView.deselectRow(at: indexPath, animated: true)
  421.        
  422.        
  423.        
  424.     }
  425.    
  426. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement