Monday, 18 November 2019

How to arrange cells into sections with a custom header?

How would I be able to arrange the cells by sections with a custom header

I have code set to arrange the cells in the CartVC by brand(the brand being placed in a Custom Header Cell) in the CartVC when the data is passed from the HomeVC to the CartVC, yet I still can't get my code arrange the cells into sections by brand

so far what Ive does is created an array in my cart to help arrange the cells in the CartVC by their Brand. After the data has been passed from the HomeVC to the CartVC.

basically what im asking is

How would I be arrange the sections by brand in the CartVC after data is passed into the Cart

image

extension HomeController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemSetup.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as? HomeCell else { return UITableViewCell() }

        let item = itemSetup[indexPath.row]
        cell.configure(withItems: item)

        // passes data to the Cart Cells in the CartVC when ATC Btn is pressed in each HomeCell
        cell.addActionHandler = { (option: Int) in
            print("Option selected = \(option)")
            Tray.currentCart.cartItems.append(item)
            item.selectedOption = option
        }

        return cell
    }
}

import UIKit

class CartViewController: UIViewController {

    var items: Items!

    // arranges cells into sections
    var tray: [Tray] = []
    var sortedBrandsByName: [String] = []
    var sections: [[Tray]] = [[]]

    //TEST CODE
    var setUp: [Tray] = []
    var groupedItems: [String: [Tray]] = [:]
    var brands: [String] = []

    @IBOutlet weak var cartTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // arranges cells into sections
        let brandNames = tray.map { $0. titleBrandName }
        let uniqueBrandNames = Array(Set(brandNames))           
        let sortedBrandNames = uniqueBrandNames.sorted()
        let sections: [[Tray]] = sortedBrandNames.map { firstBrandNames in
            return tray
                .filter { $0. titleBrandName == firstBrandNames } 
                .sorted { $0.cart.brand < $1.cart.brand } // sort them
        }

        // Do any additional setup after loading the view.
        cartTableView.dataSource = self
        cartTableView.delegate = self

    // TEST CODE
    groupedItems = Dictionary(grouping: setUp, by: {$0.cart.brand})
    brands = groupedItems.map{$0.key}.sorted()

    }
}

extension CartViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        //allows data passed from the HomeVC populate the CartCells
        return Tray.currentCart.cartItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CartCell", for: indexPath) as! CartCell

        // **Active code** that allows data passed from the HomeVC populate the CartCells
        let cart = Tray.currentCart.cartItems[indexPath.row]
        cell.configure(withItems: cart)

        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cartHeader = tableView.dequeueReusableCell(withIdentifier: "CartHeaderCell") as! CartHeaderCell

        return cartHeader
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45
     } 
}

class CartHeaderCell: UITableViewCell {

    @IBOutlet weak var brandName: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}

class CartCell: UITableViewCell {

    @IBOutlet weak var lblMealName: UILabel!
    @IBOutlet weak var imageUrl: UIImageView!
    @IBOutlet weak var lblSubTotal: UILabel!
    @IBOutlet weak var lblQty: UILabel!

    override func awakeFromNib() {
         super.awakeFromNib()
        // Initialization code
    }

    // allows the data to be passed into the cart cells

    func configure(withItems items: ProductList) {
        imageUrl.sd_setImage(with: URL(string: items.imageUrl))
        lblQty.text = "\(items.count)"
        let formatter = NumberFormatter()
        formatter.maximumFractionDigits = 2
        formatter.numberStyle = .decimal
        if items.selectedOption == 1 {
            lblSubTotal.text = "$\(formatter.string(for: items.price1 * Float(items.count))!)"
            lblMealName.text = "\(items.name) ● \(items.weight1)"
        } else if items.selectedOption == 2 {
            lblSubTotal.text = "$\(formatter.string(for: items.price2 * Float(items.count))!)"
            lblMealName.text = "\(items.name) ● \(items.weight2)"
        } else if items.selectedOption == 3 {
            lblSubTotal.text = "$\(formatter.string(for: items.price3 * Float(items.count))!)"
            lblMealName.text = "\(items.name) ● \(items.weight3)"
        }
    } 
}

// allows the code that is passed to the CartVC when an item is passed from the HomeVC to the CartVC
class Tray {
    static let currentCart = Tray()
    var cartItems = [Items]()
    var cart: Items!
    var sectionTitle: String!
}

extension Tray {
    var titleBrandName: String {
        return String(self.cart.brand[self.cart.brand.startIndex]).uppercased()
    }
}


class Items {
    var id: String
    var name: String
    var brand: String
    var price1: Float
    var price2: Float
    var price3: Float
    var weight1: String
    var weight2: String
    var weight3: String
    var imageUrl: String
    var count: Int
    var selectedOption: Int

    init(id: String,
         name: String,
         brand: String,
         price1: Float,
         price2: Float,
         price3: Float,
         weight1: String,
         weight2: String,
         weight3: String,
         imageUrl: String,
         count: Int,
         selectedOption: Int) {

        self.id = id
        self.name = name
        self.brand = brand
        self.price1 = price1
        self.price2 = price2
        self.price3 = price3
        self.weight1 = weight1
        self.weight2 = weight2
        self.weight3 = weight3
        self.imageUrl = imageUrl
        self.count = count
        self.selectedOption = selectedOption

    }

    convenience init(dictionary: [String : Any]) {
        let id = dictionary["id"] as? String ?? ""
        let name = dictionary["name"] as? String ?? ""
        let brand = dictionary["brand"] as? String ?? ""
        let price1 =  dictionary["price1"] as? Float ?? 0.0
        let price2 =  dictionary["price2"] as? Float ?? 0.0
        let price3 =  dictionary["price3"] as? Float ?? 0.0
        let weight1 =  dictionary["weight1"] as? String ?? ""
        let weight2 =  dictionary["weight2"] as? String ?? ""
        let weight3 =  dictionary["weight3"] as? String ?? ""
        let imageUrl =  dictionary["imageUrl"] as? String ?? ""
        let count = dictionary["count"] as? Int ?? 00
        let selectedOption = dictionary["selectedOption"] as? Int ?? 00

        self.init(id: id,
                  name: name,
                  brand: brand,
                  price1: price1,
                  price2: price2,
                  price3: price3,
                  weight1: weight1,
                  weight2: weight2,
                  weight3: weight3,
                  imageUrl: imageUrl,
                  count: count,
                  selectedOption: selectedOption)
    }

}


from How to arrange cells into sections with a custom header?

No comments:

Post a Comment