user8194455
user8194455

Reputation:

UILabel Not Changing Text

I have created an array in a tableView to record how many cells have checkmarks or not, and tried to have the Label text change based on how many checkmarks there are.

My code:

@IBOutlet weak var myLabel: UILabel!
func setText() {

    if checkmarks == [0: false] {
    self.myLabel.text = "text"
    }
    if checkmarks == [1: false] {
    self.myLabel.text = "text1"
    }
} 

I am not getting any errors, but the text is not changing. Any advice is appreciated.

UPDATE: The array I am trying to take values from is in another class.

Here is that code:

var checkmarks = [Int: Bool]()

the checkmarks get saved so I thought by writing the above code in a (public class??), my other class files could access it.

Perhaps I need to call checkmarks at the start of the other class file too? Edit: That is an invalid redeclaration my bad.

Thanks for the help

UPDATE 2: The problem was in the interpretation of the array system. I rewrote my code as a loop (which I will add on request) and that fixed it. Thank you all for helping!!

Upvotes: 1

Views: 307

Answers (1)

Jayachandra A
Jayachandra A

Reputation: 1342

as of my understanding you are trying to show the selected row with tick mark in a tableview, so if it then there is another approach to show it.

consider the following approach.

declare your variables as global to class

var selected = [String]()
let colors = ["Apple","Pear", "Banana","Orange",]

and your datasource and delegate methods should like similar to this

    extension ViewController: UITableViewDataSource, UITableViewDelegate {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.selectionStyle = .none
            if selected.contains(colors[indexPath.row]) {
                cell.accessoryType = .checkmark
            }else{
                cell.accessoryType = .none
            }
            cell.textLabel?.text = colors[indexPath.row]
            return cell;
        }

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

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            if selected.contains(colors[indexPath.row]) {
                selected.remove(at: selected.index(of: colors[indexPath.row])!)
            }else{
                selected.append(colors[indexPath.row])
            }
            tableView.reloadData()
        } 
}

and finally your output will be like this enter image description here

Upvotes: 1

Related Questions