Created
March 23, 2013 17:58
-
-
Save twerth/5228758 to your computer and use it in GitHub Desktop.
A simple example of creating a UIView with a UICollectionView as a subview in RubyMotion using Teacup for styling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A simple example of creating a UIView with a UICollectionView as a subview | |
# in RubyMotion using Teacup for styling | |
# | |
# Your controller will need to set the stylesheet: stylesheet :example | |
# and create this view like so: subview Example, :my_example_view | |
class Example < UIView | |
CELL_IDENTIFIER = 'example_cell' | |
def initWithFrame(frame) | |
if super | |
# Create UICollection View | |
layout = UICollectionViewFlowLayout.alloc.init | |
cv = UICollectionView.alloc.initWithFrame(self.bounds, collectionViewLayout: layout) | |
cv.registerClass(ExampleCell, forCellWithReuseIdentifier: CELL_IDENTIFIER) | |
@collection = subview(cv, :collection, delegate: self, dataSource: self) | |
end | |
self | |
end | |
def numberOfSectionsInCollectionView(view) | |
30 # Number of sections | |
end | |
def collectionView(view, numberOfItemsInSection: section) | |
rand(10) # Number of cells in this section | |
end | |
def collectionView(view, cellForItemAtIndexPath: index_path) | |
view.dequeueReusableCellWithReuseIdentifier(CELL_IDENTIFIER, forIndexPath: index_path).tap do |cell| | |
layout(cell.contentView, :cell) do | |
# No not add subviews here, as this cell may already exist. Add them in ExampleCell below | |
cell.label.text = "#{index_path.section}/#{index_path.row}" | |
end | |
end | |
end | |
end | |
class ExampleCell < UICollectionViewCell | |
attr_accessor :label | |
def initWithFrame(frame) | |
if super | |
layout self.contentView do | |
# Add subviews here | |
@label = subview(UILabel, :cell_label) | |
end | |
end | |
self | |
end | |
end | |
Teacup::Stylesheet.new :example do | |
style :collection, | |
frame: :full, | |
backgroundColor: UIColor.clearColor, | |
autoresizingMask: UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight, | |
allowsSelection: false, | |
collectionViewLayout: { | |
itemSize: [100, 40], | |
sectionInset: [10,10,10,10], | |
minimumInteritemSpacing: 5, | |
minimumLineSpacing: 5 | |
} | |
style :cell, | |
frame: :full, | |
backgroundColor: UIColor.whiteColor | |
style :cell_label, | |
height: 15, width: 50, top: 5, left: 5, | |
textColor: UIColor.blackColor, | |
backgroundColor: UIColor.clearColor | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should I be able to use didSelectItemAtIndexPath using this method, or is there an issue with having the UIView as the delegate?