vendredi 8 juillet 2016

select row and add/remove Checkmark and add amount swift

I have a table view in a view controller and the result I want to achieve is to add 5 to var mytotal for row 1...4 if the row is selected and subtract 5 if the row is deselected.

For the 5th row (the last one) I want to add 10 if the row is selected and subtract 10 if the row is deselected. Every time a row is selected a checkmark is added to the right of the cell and when the row is deselected the checkmark is removed.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var mytotal: UILabel!
var total = 0
@IBOutlet weak var tableView: UITableView!

var items = ["Inside Cabinets", "Inside Fridge", "Inside Oven", "Interior windows","Laundry wash & dry"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")


}

// number of rows in table
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return self.items.count
}

    // create the cells
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

    var cell = self.tableView.dequeueReusableCellWithIdentifier("myCell")!
    cell.textLabel!.text = self.items[indexPath.row]
    cell.accessoryType = UITableViewCellAccessoryType.None
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
    var theCell = tableView.cellForRowAtIndexPath(indexPath)!


    if theCell.accessoryType == .None {
        theCell.accessoryType = .Checkmark
        total += 5
    self.mytotal.text = String(total)
    }
    else if theCell.accessoryType == .Checkmark {
        theCell.accessoryType = .None

        total -= 5
    self.mytotal.text = String(total)
    }

}


}

Aucun commentaire:

Enregistrer un commentaire