Swift: Bool 如果为真,不显示图像

Swift: Bool if true, doesn't display image

我是初学者,请耐心讲解,谢谢

所以,基本上我在解析中有一个 bool 列,如果图像为假,我想显示它,如果为真,则不显示任何内容。

这是我的代码:

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 object["reqRead"] as! Bool == false {

                    myCell.isRead.image = nil 
                    myCell.isRead.hidden = false

                } else {

                    myCell.isRead.hidden = true

                }

这听起来像是三元运算符的理想用例。按照我下面的示例,您使用 ? : Bool 之后的语法,如果 bool 为真,它将 return 第一种情况,如果为假,它将 return 第二种情况。

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")

            }
        }
    })

更新

上述方法可能无效,因为 Parse 调用可能未在加载单元格之前完成。

创建一个全局变量(在任何函数之外):

var reqRead = [Bool]()

在 ViewDidLoad 中,您可以创建一个布尔数组。

    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()
    }
})

然后在您的 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

}

它可能会在加载数组之前尝试填充单元格,但请告诉我这是否适合您。