-4

I need swift code in my ViewController one table view, label, AddButton. In tableview 8 customcells are there, in each cell one label,(-, +) buttons are there. If I press '+' label value must increase while if I press '-' label value decrease, same way happen to each and every cell. Finally, if I press AddButton the total must be added and it displays in a label in viewcontroller Thanks, InAdvance. image in viewController tableview methods

   @IBOutlet var tableviewObj: UITableView!

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return 8
}
public func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented
{
    return 1
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
           if indexPath.row  == 0 {
        let cell:firstTableViewCell = tableView.dequeueReusableCell(withIdentifier: "first") as! firstTableViewCell
        return cell
    }
    else if indexPath.row == 1 {
       let cell:secondTableViewCell = tableView.dequeueReusableCell(withIdentifier: "second") as! secondTableViewCell
                 return cell
    }
     else if indexPath.row == 2 {
       let cell:thirdTableViewCell = tableView.dequeueReusableCell(withIdentifier: "third") as! thirdTableViewCell
        return cell
    }
   else if indexPath.row == 3 {
        let cell:fourthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fourth") as! fourthTableViewCell
        return cell
    }
    else if indexPath.row == 4 {
        let cell:fifthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "fifth") as! fifthTableViewCell
        return cell
    }
    else if indexPath.row == 5 {
        let cell:sixthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sixth") as! sixthTableViewCell
        return cell
    }
        else if indexPath.row == 6 {
       let cell:seventhTableViewCell = tableView.dequeueReusableCell(withIdentifier: "seven") as! seventhTableViewCell
        return cell
    }else  {
        let cell:eighthTableViewCell = tableView.dequeueReusableCell(withIdentifier: "eight") as! eighthTableViewCell
        return cell
    }
}
 @IBOutlet var labelObj: UILabel!
@IBAction func Total(_ sender: Any) {

   // i need code here


}
class firstTableViewCell: UITableViewCell {
@IBOutlet var labelObj: UILabel!
var cur = 0
var str = ""

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

}

@IBAction func Minus(_ sender: Any) {
            if (self.labelObj.text == "1") {
        self.labelObj.text = String( 1)

    }else
            {
                cur = Int(labelObj.text!)!
                self.labelObj.text = String(cur - 1)
                str = self.labelObj.text!

                print(str)
    }
}
@IBAction func Add(_ sender: Any) {
    cur = Int(labelObj.text!)!
    self.labelObj.text = String(cur + 1)

    str = self.labelObj.text!

    print(str)


}
Vinodh
  • 5,262
  • 4
  • 38
  • 68
chandra1234
  • 357
  • 6
  • 15
  • please add some code – ekans Jan 17 '18 at 11:10
  • 1
    Your question needs to include at least some code that you have tried already, otherwise it looks like you are just asking someone to code it for you. We're glad to help so please update your question with what you have already tried and we can help you from there. – davidethell Jan 17 '18 at 11:11
  • 2
    wow. but nope. try to use one prototype cell with a delegate deal with user interactions and you also need to establish the _model_ where you can store in / restore from the current value for the actual row. – holex Jan 17 '18 at 11:36
  • Welcome to Stack Overflow. Check the Stack Overflow's [help on asking questions](http://stackoverflow.com/help/asking) first, please. Focus on [What topics can I ask about here](http://stackoverflow.com/help/on-topic), [What types of questions should I avoid asking?](http://stackoverflow.com/help/dont-ask), [How to ask a good question](http://stackoverflow.com/help/how-to-ask), [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and [Stack Overflow question checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – David Ferenczy Rogožan Jan 17 '18 at 11:41
  • Your code does not follow standard iOS coding practices - you should be only dequeuing a single cell and using delegates to update a model. I strongly recommend you follow a tutorial first. – Robotic Cat Jan 17 '18 at 13:21
  • thanks @RoboticCat But I'm new to swift – chandra1234 Jan 17 '18 at 13:24
  • Everyone is a beginner at some point so that is not a problem. But this is not to do with Swift; it's to do with learning the iOS frameworks and how they function. There are hundreds of tutorials on `UITableView` which can be done in less than an hour after which it will be obvious about how you should re-structure your code to solve your problems. – Robotic Cat Jan 17 '18 at 14:00

1 Answers1

1

Create a model to hold the value of the label in a cell-like below

struct Product {
    var price = 0
}

We need to communicate from cell to viewcontroller so we need a protocol like a below

protocol CartSelection {
    func addProductToCart(product : Product, atindex : Int)
}

I have created array to show in tableview. And I will pass the product to cell. So ViewController code is :

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,CartSelection {

    @IBOutlet weak var totalLabel: UILabel!

    var productArray = [Product]()

    @IBOutlet weak var testTableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        for _ in 0...10{
            productArray.append(Product(price: 1))
        }
        testTableview.allowsSelection = false
        calculateTotal()
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TestTableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TestTableViewCell
        cell.product = productArray[indexPath.row]
        cell.valueLabel.text = "\(cell.product.price)"
        cell.productIndex = indexPath.row
        cell.cartSelectionDelegate = self

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }

    @IBAction func addBtnPressed(_ sender: UIButton) {

    }

    func addProductToCart(product: Product, atindex: Int) {
        productArray[atindex] = product

        calculateTotal()
    }

    func calculateTotal()
    {
        var totalValue = 0
        for objProduct in productArray {

            totalValue += objProduct.price
        }

        self.totalLabel.text = "Total \(totalValue)"

    }

}

and TableViewCell code like below :

class TestTableViewCell: UITableViewCell {
    var product : Product!
    private var counterValue = 1
    var productIndex = 0

    var cartSelectionDelegate: CartSelection?

    @IBOutlet weak var valueLabel: UILabel!

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

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    @IBAction func minusButton(_ sender: UIButton) {
        if(counterValue != 1){
            counterValue -= 1;
        }
        self.valueLabel.text = "\(counterValue)"
        product.price = counterValue
        cartSelectionDelegate?.addProductToCart(product: product, atindex: productIndex)
    }
    @IBAction func plusButton(_ sender: UIButton){
        counterValue += 1;
        self.valueLabel.text = "\(counterValue)"
        product.price = counterValue
        cartSelectionDelegate?.addProductToCart(product: product, atindex: productIndex)

    }
}

Output will look like the screenshot below

Initial Stage

After changing value in cell

Vinodh
  • 5,262
  • 4
  • 38
  • 68