在imageView数组中设置图像?

时间:2015-07-13 00:40:09

标签: ios swift uitableview uiimageview uiimage

我遇到了一个我不确定如何解决问题的问题。我有一个Cell对象,我创建了一些IBOutlets,我希望在我的UITableView内显示我的屏幕,如下所示:

class EventCell: UITableViewCell, CellDelegate{   
    @IBOutlet var eventName: UILabel!
    @IBOutlet var eventLocation: UILabel!
    @IBOutlet var attendeesImages: [UIImageView]!
}

我还有另一个功能,我尝试设置该单元格的单元格内容,如下所示:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //Dequeue a "reusable" cell
    let cell = tableView.dequeueReusableCellWithIdentifier(eventCellIdentifier) as! EventCell
    setCellContents(cell, indexPath: indexPath)
    return cell
}

//Set contents of Event Cell.. self.events is a global array
//which have information that EventCell objects need to display

func setCellContents(cell:EventCell, indexPath: NSIndexPath!){
    let item = self.events[indexPath.section]
    var count = 0

    cell.eventName.text = item.eventName()
    cell.eventLocation.text = item.eventLocation()

    //Attempt to set the cell.attendeesImage values
    for value in item.attendeesImages() {
        cell.attendeesImages[count].image = value
        cell.attendeesImages[count].clipsToBounds = true
        cell.attendeesImages[count].layer.cornerRadius = cell.attendeesImage[count].frame.size.width / 2
        count++
    }
}

问题是,当我尝试设置cell.attendeesImages的值时,我遇到了fatal error: Array index out of range的问题。问题是因为我正在访问cell.attendeesImages中不存在的索引。在分配内容之前,有没有办法分配或设置cell.attendeesImages的大小?或者只是在cell.attendeesImages内分配图像的更好方法?我还尝试将cell.attendeesImages设置为UIImage并设置cell.attendeesImages = item.attendeesImages的数组,但如果它是UIImage,我似乎无法将图像显示在屏幕上而UIImageView允许我这样做。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

替换

for value in item.attendeesImages() {
    cell.attendeesImages[count].image = value
    cell.attendeesImages[count].clipsToBounds = true
    cell.attendeesImages[count].layer.cornerRadius = cell.attendeesImage[count].frame.size.width / 2
    count++
}

使用

for (count, value) in enumerate(item.attendeesImages()) {

    var workingImage : UIImageView! = nil
    if count >= cell.attendeesImages.count {
        workingImage = UIImageView(image : value)
        cell.addSubview(workingImage)
        cell.attendeesImages.append(workingImage)

        //TODO: Layout image based on count
    } else {
        workingImage = cell.attendeesImages[count]
    }

    workingImage.clipsToBounds = true
    workingImage.layer.cornerRadius = workingImage.frame.size.width / 2
}

//Loop through remaining images from cell-reuse and hide them if they exist
for var index = item.attendeesImages().count; index < cell.attendeesImages.count; ++index {

    cell.attendeesImages[index].image = nil
}