Skip to content

How to declare a view class?

Zhang Kai Yu edited this page Apr 27, 2015 · 2 revisions

A view class can be declared this way, very similar to Apple's AppKit view or UIKit view.

# Table cell used in a table view
class MYAPP.ContactCellView extends CB.View

  constructor: () ->
    super()
    @nameLabel = new CB.LabelView()
    @nameLabel.font = "Avenir"
    @nameLabel.textColor = "black"
    @emailLabel = new CB.LabelView()
    @emailLabel.textColor = "gray"
    @avatarImageView = new CB.ImageView()
    this.addSubview(@nameLabel)
    this.addSubview(@emailLabel)
    this.addSubview(@avatarImageView)

  @property "contactName",
    set: (newValue) -> @_contactName = newValue; @nameLabel.text = newValue;
  
  @property "contactEmail",
    set: (newValue) -> @_contactEmail = newValue; @emailLabel.text = newValue;

  @property "contactAvatarURL",
    set: (newValue) -> @_contactAvatarURL = newValue; @avatarImageView.url = newValue;

  @property "nameLabel"

  @property "emailLabel"

  @property "avatarImageView"

  layoutSubviews: () ->
    super()
    cellFrame = @frame
    cellHeight = cellFrame.size.height
    cellWidth = cellFrame.size.width
    margin = 8
    nameLabelHeight = 30
    emailLabelHeight = 18
    avatarWidth = avatarHeight = myHeight - 16
    labelWidth = cellWidth - 3 * margin - avatarWidth
    @nameLabel.frame = new CB.Frame(margin, margin, labelWidth, nameLabelHeight)
    @emailLabel.frame = new CB.Frame(margin, nameLabelHeight + margin * 2, labelWidth, emailLabelHeight)
    @avatarImageView.frame = new CB.Frame(labelWidth + 2 * margin, margin, avatarWidth, avatarHeight)
    @avatarImageView.cornerRadius = avatarWidth / 2