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

时间:2016-02-23 08:38:04

标签: swift parse-platform tableviewcell

我是初学者所以请耐心解释,谢谢。

所以,基本上我在解析时有一个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")

                    }


                }
            }
        })

如果我没有正确解释,请告诉我,我会尽力再解释一下。

2 个答案:

答案 0 :(得分:2)

这听起来像是三元运算符的理想用例。按照下面的例子,你使用? :bool之后的语法,如果bool为true,它将返回第一个case,如果为false,则返回第二个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")

            }
        }
    })

<强>更新

由于在加载单元格之前可能无法完成Parse调用,因此上述操作可能无效。

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

var reqRead = [Bool]()

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

    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

}

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

答案 1 :(得分:0)

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

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

                } else {

                    myCell.isRead.hidden = true

                }