tableView(tableView:, cellForRowAtIndexPath:) -> UITableViewCell方法中,如何通过单元格设置可选的imageView?

在这种情况下,如果cell!.imageView?.image = someLoadedImageimageView: UIImageView?属性是cell,那么分配将失败,对吧?

根据《 Swift编程指南》的nil,“在此示例中,由于john.residence当前为nil,因此设置john.residence的address属性的尝试将失败”(可选的链接章节)。

class Residence {
    ...
    var address: Address?
}
class Person {
    var residence: Residence?
}
let john = Person()
let someAddress = Address()
john.residence?.address = someAddress // will fail


这是代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier)
            as? UITableViewCell
        if cell == nil {
            cell = UITableViewCell(style: .Default, reuseIdentifier: simpleTableIdentifier)
        }
        let image = UIImage(named: "star")
        let highlightedImage = UIImage(named: "star2")
        cell!.imageView?.image = image // can compile and run
        cell!.imageView?.highlightedImage = highlightedImage

        cell?.textLabel!.text = dwarves[indexPath.row]
        return cell!
    }

最佳答案

我们有理由检查单元格是否为零,因为如果队列中当前没有可用的可重用单元格可供使用,那么我们必须创建一个新的单元格。

关于ios - 如何设置UITableViewCell的imageView?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32078628/

10-15 07:24