0

我使用以下方法创建一个单元格并在其中填充数据(改编自推文应用程序示例) 现在我想添加一个显示所选事件日期的新标签和一个将执行另一个操作的按钮。这里有2种方法:

def self.cellForEvent(event, inTableView:tableView)
    cell = tableView.dequeueReusableCellWithIdentifier(EventCell::CellId) || EventCell.alloc.initWithStyle(UITableViewCellStyleDefault, reuseIdentifier:CellId)
    cell.fillWithEvent(event, inTableView:tableView)
    cell.accessoryType =  UITableViewCellAccessoryDetailDisclosureButton
    cell
end

将数据填充到单元格中

def fillWithEvent(event, inTableView:tableView)
    self.textLabel.text = event.name
    puts event.image
    unless event.image
      self.imageView.image = nil
      Dispatch::Queue.concurrent.async do
        event_image_data = NSData.alloc.initWithContentsOfURL(NSURL.URLWithString(event.image_url))
        if event_image_data
          event.image = UIImage.alloc.initWithData(event_image_data)
          Dispatch::Queue.main.sync do
            self.imageView.image = event.image
            tableView.delegate.reloadRowForEvent(event)
          end
        end
      end
    else
      self.imageView.image = event.image
    end
  end
4

1 回答 1

0

railsdog 的推荐并非没有道理。您可以对要编辑的单元格进行@reference,然后再对其进行更改。但这有点危险——有很多陷阱:如果单元格被移出屏幕会发生什么?在其他地方重复使用?棘手。

相反,我建议将一些fillWithEvent:inTableView代码添加到cellForEvent方法中,这样您就可以调用tableView.reloadRowsAtIndexPaths:withRowAnimation:并且将调用该方法。这将我上面提到的复杂性转移到 Cocoa 框架的后面,这是一件好事:-)

不利的一面是您需要保持 indexPath 方便(或可计算),并始终记住event与单元格相关联是瞬态的,因为单元格被重用。您上面的代码似乎没有保留对 的引用event,这是一件好事!

# in fetchImageForEvent:tableView:
# ...
event.image = UIImage.alloc.initWithData(event_image_data)
Dispatch::Queue.main.sync do
  # instead of this:
  # self.imageView.image = event.image

  # tell the tableView to reload.  unfortunately, we don't have the index
  # path.  not sure how you're calculating it, but if you've got a list of
  # events, this should be easy.
  # I'm just assuming section 0, row 1 here.
  path = NSIndexPath.indexPathWithIndex(0).indexPathByAddingIndex(1)
  tableView.reloadRowsAtIndexPaths([path], withRowAnimation:UITableViewRowAnimationAutomatic)
end
于 2013-03-07T14:47:52.310 回答