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 に答える