简体   繁体   中英

Swift Tableview Cells populated with name and a Int value

I'm trying to build my first app and i'm hitting a wall

I have a view controller and inside this view controller is a UITableView

Now I have been able to populate this view controller using an array.count

I have been able to add an accesory checkmark when i tap on the item to mark sa completed

Now my problem is that i want to tap on an item, mark it as completed AND when completed to have a value written on a label

each cell would have a different Int value

I've read somewhere that to do so i would need to use NSMutableArray but i don't know how to use this

any help would be really appreciated

heres the code :

UPDATED may 8 1215 utc

import UIKit

// --------------------------------------------------------------------------------------------------------------------------\
class ViewController: UIViewController, UITableViewDataSource {                        //class and subclass                  |)
//---------------------------------------------------------------------------------------------------------------------------/
    // Variable and constant, also IBAOutlet


    struct CellData
    {
        var title: String
        var value: String
        var selected: Bool

    }

    var CellData1 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData2 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData3 = CellData(title: "this is a test", value: "1", selected: true)
    var CellData4 = CellData(title: "this is a test", value: "1", selected: true)

    var tableArray: [CellData] = []

    @IBOutlet weak var scoreshow: UILabel!
    @IBOutlet weak var tableView: UITableView!

// --------------------------------------------------------------------------------------

    override func viewDidLoad() {

        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
    }
//----------------------------------------------------------------------------------------
    // checkmarks when tapped

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if let cell = tableView.cellForRowAtIndexPath(indexPath) {
            if cell.accessoryType == .Checkmark
            {
                cell.accessoryType = .None
                cell.backgroundColor = UIColor.whiteColor()
            }
            else
            {
                cell.accessoryType = .Checkmark
                cell.backgroundColor = UIColor.yellowColor()            }
        }    
    }

//----------------------------------------------------------------------------------------
    //number of sections for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 5
    }
//----------------------------------------------------------------------------------------
    //Calculate the amount of rows

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return self.tableArray.count;
    }
//----------------------------------------------------------------------------------------
    //Cells text label and config

    func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{


        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
        cell.textLabel!.text = (tableArray[indexPath.row]).title
        scoreshow.text = (tableArray[indexPath.row]).value
        cell.textLabel!.numberOfLines = 0
        cell.selectionStyle = UITableViewCellSelectionStyle.None;

        return cell
 }

//----------------------------------------------------------------------------------------
    //resetbutton

    @IBAction func resetcheck(sender: UIButton) {

            for i in 0...tableView.numberOfSections()-1
            {
                for j in 0...tableView.numberOfRowsInSection(i)-1
                {
                    if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) {
                        cell.accessoryType = .None
                        cell.backgroundColor = UIColor.whiteColor()
                    }

                }
            }
        }

//----------------------------------------------------------------------------------------

So first what you should probably do is create a new subclass of NSObject and set it up so it takes properties such as objectText and objectValue.

You then create as many objects as you want and store these in an NSMutableArray

NSMutableArrays are the same as what you have done here..

let section1 =
    ["this is used",
     "this is used to test",
     "this is used to test the lenght",
     "this is used to test the lenght of the text",
     "this is used to test the lenght of the text",
     "this is used to test the lenght of the text",
     "this is used to test the lenght of the text",
     "this is used to test the lenght of the text",
     "this is used to test the lenght of the text",]

Sort of... except you will want to make it a var rather than let so that you can modify it.

You'd end up with something like:

let object1: MyNewModel = MyNewModel("this is used", value: 1)
section1.append(object1)

That's if you create a decent init method for your model that you can easily set it up.

You can now use this mutable array to populate your tableview in the same way as you are doing, but instead of just setting the text to that object in the array you would set it to:

((MyNewModel)section1[indexPath.row]).objectText

The next thing you'll want to do is subclass UITableViewCell and inside the cell position some labels that you wish to populate with the text inside these models. So give them some public properties to access the labels inside the table cell, replace this line:

let cell:UITableViewCell =
UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")

With this:

let cell = MyNewTableCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")

You will then have access to your new labels inside the cell and set them as so:

cell.myTextLabel!.text = ((MyNewModel)section1[indexPath.row]).objectText
cell.myValueLabel!.text = ((MyNewModel)section1[indexPath.row]).objectValue

And you can hide or show whichever you want to show whenever..

You need to change your approach.

When the user does something to a cell (like select it) you are grabbing the cell (using tableView.cellForRowAtIndexPath() ) and changing it.

That is the wrong way to do things.

What you want to do is have an array (mutable array, or a var array in Swift) that records the current state of your able view. Text contents, integer values, selected state, etc.

Then in cellForRowAtIndexPath , configure the cell using the data in the array.

If the user taps a cell, fetch the array entry for that cell, change it, and then tell the table view to redraw that cell (using reloadRowsAtIndexPaths).

I would suggest creating a struct to store all the info for your cell:

struct CellData
{
  var title: String
  var value: Int
  var selected: Bool
}

...

var tableArray: [CellData]

Then write your cellForRowAtIndexPath method to configure the cell by fetching those values from your array of structs.

Your code creates 3 different immutable arrays section1, section2, and section3, but then numberOfSectionsInTableView returns a fixed value of 5, and cellForRowAtIndexPath always returns cells built from section1. That's screwy.

If you're just playing, skip sectioned table views for now. It will confuse you. Start with a single-sectioned table view, get the hang of that, and then deal with sectioned tableviews later.

When you are ready for sectioned table views, try using an array of arrays:

//The array for a section is an array of CellData
typealias sectionArray: [CellData] 

//The array for the whole table is an array of sectionArray arrays.
var tableArray: [sectionArray]

init()
{
  tableArray = [ 
    sectionArray[
      CellData(title:"section 0, row 0", value: 0, selected: false],
      CellData(title:"section 0, row 1", value: 1, selected: false],
      CellData(title:"section 0, row 2", value: 2, selected: false]
    ],
    sectionArray[
      CellData(title:"section 1, row 0", value: 10, selected: false],
      CellData(title:"section 2, row 1", value: 11, selected: false],
      CellData(title:"section 3, row 2", value: 12, selected: false]
    ]
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM