Arash Allahmorad Arash Allahmorad - 4 months ago 10
Swift Question

Swift: Bool if true, doesn't display image

I'm a beginner so please be patient explaining, Thanks.

So, basically I have a bool column in parse and I want to display an image if it's false and don't display anything if its true.

here are my codes:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("todayCell", forIndexPath: indexPath) as! reqTodaysCell
let cellDataParse: PFObject = self.dataparse.objectAtIndex(indexPath.row) as! PFObject

var newReadQuery = PFQuery(className: "request")
newReadQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {

if object["reqRead"] as! Bool == true {

myCell.isRead.image = nil //here is where I say pic to be nil but what happens is that if the first one is true then it will remove the pic for all of them.
// and if its not true it should display the pic

} else {

myCell.isRead.image = UIImage(named: "newReq")
print("user not read")

}


}
}
})


If I don't explain properly please let me know and I will try my best to explain again.

Answer

This sounds like an ideal use case for a ternary operator. As per my example below, you use the ? : syntax following a Bool, if the bool is true it will return the first case and if it's false it will return the second case.

newReadQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
        if let objects = objects {
            for object in objects {

              let reqRead = object["reqRead"] as! Bool

              cell.image.image = reqRead ? nil : UIImage(named: "newReq")

            }
        }
    })

UPDATE

The above may not have worked as the Parse call might not be completed before the cells are loaded.

Create a global variable (outside of any function):

var reqRead = [Bool]()

In ViewDidLoad you can create an array of the bools.

    var newReadQuery = PFQuery(className: "request")
 newReadQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
    if let objects = objects {

        for object in objects {

          reqRead.append(object["reqRead"] as! Bool)

        }
      tableView.reloadData()
    }
})

Then in your CellForRow:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("todayCell", forIndexPath: indexPath) as! reqTodaysCell      
    let cellDataParse: PFObject = self.dataparse.objectAtIndex(indexPath.row) as! PFObject

cell.image.image = reqRead[indexPath.row] ? nil : UIImage(named: "newReq")

return cell

}

There's a possibility that it will try to populate the cells before the array is loaded but let me know if this works for you.