This project has been sunset in favor of MotionKit
A community-driven DSL for creating user interfaces on iOS and OS X. Using Teacup, you can create and style layouts and keeping your code dry. The goal is to offer a rubyesque (well, actually a rubymotion-esque) way to create interfaces programmatically.
Read a letter from Colin T.A. Gray regarding the future of Teacup and introducing MotionKit, its successor.
Quick Install
> gem install teacupand in your Rakefile
require 'teacup'UIViewController subclass:…In your AppDelegate you need to call Teacup::Appearance.apply. It will get
called automatically using the UIApplicationDidFinishLaunchingNotification,
but that notification is triggered after the method
AppDelegate#didFinishLaunching(withOptions:) is called.
class AppDelegate
def didFinishLaunching(application, withOptions:options)
Teacup::Appearance.apply
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
ctlr = MainController.new
@window.rootViewController = UINavigationController.alloc.initWithRootController(ctlr)
@window.makeKeyAndVisible
true
end
endThat block is called using the UIApplicationDidFinishLaunchingNotification,
but that notification is not called until the end of the
application(application,didFinishLaunchingWithOptions:launchOptions) method.
This is sometimes after your views have been created, and so they will not be
styled. If that is the case, call Teacup::Appearance.apply before creating
your rootViewController.
You have enough information right now to go play with Teacup. Check out the
example apps, write your own, whatever. But read on to hear about why Teacup is
more than just writing layouts and applying styles.
You should also be sure to read the Misc notes section at the bottom. These aren't very well organized, but the information is important. You can learn about features any time, but learning about the "gotcha"s sooner rather than later could save you a lot of time!
When you are prototyping an app it is useful to bang out a bunch of code quickly, and here are some ways that Teacup might help.
You can use all the methods above without having to rely on the entirety of Teacup's layout and stylesheet systems. By that I mean any time you are creating a view hierarchy don't be shy about using Teacup to do it.
UIView and NSView have the style method, which can be used to group a
bunch of customizations anywhere in your code. You don't have to pull out a
stylesheet to do it.
…Teacup is designed to be used in coordination with the controller life cycle, but there are other life cycles that need to be considered as well. UITableViews maintain a "queue" of cells that can be reused, and they need to be restyled when the cell is created and re-used.
The solution is to apply the styles and layout constraints inside the
tableView:willDisplayCell:forRowAtIndexPath: delegate method. In your
delegate, if you include the Teacup::TableViewDelegate module, you'll get this
behavior for free, and if you override this method, you can call super to have
the Teacup method run.
class TableViewController "title #{index_path.row}")
cell.details_label = subview(UILabel, :details_label, :text => "details #{index_path.row}")
cell.other_label = subview(UILabel, :other_label, :text => "other #{index_path.row}")
end
return cell
end
# This method is implemented by the Teacup::TableViewDelegate. If you need
# to implement it, be sure to call super.
# def tableView(tableView, willDisplayCell:cell, forRowAtIndexPath:indexPath)
# super
# end
endConstraints and styles get applied before the view appears, even if the cell is reused later.
There are a few (OK, a bunch) more features that Teacup provides that deserve discussion:
Styling a UIView is fun, but a UIView is often composed of many objects, like
the layer, or maybe an imageView or textLabel and so on. You can style
those, too!
# UITableViewCells have a contentView, a backgroundView, imageView, textLabel,
# detailTextLabel, and a layer! whew!
style :tablecell,
layer: { # style the layer!
shadowRadius: 3
},
backgroundView: { # style the background!
backgroundColor: UIColor.blackColor
},
imageView: { # style the imageView!
contentMode: UIViewContentModeScaleAspectFill
}iOS only
There's more to stylesheets than just translating UIView setters. Teacup can
also apply orientation-specific styles. These are applied when the view is
created (using the current device orientation) and when a rotation occurs.
Teacup::Stylesheet.new :main do
# this label hides when the orientation is landscape (left or right)
style :label,
landscape: {
hidden: true
},
portrait: {
hidden: false
}
endCombine these styles with [Frame Calculations][calculations] to have you view frame recalculated automatically.
We've already seen the Teacup related properties:
stylename, the primary style namestyle_classes, secondary style namesstyle, apply styles directlyEach of these has a corresponding method that you can use to facilitate animations.
animate_to_stylename(stylename)animate_to_styles(style_classes)animate_to_style(properties)On OS X you have to use the view.animator property to perform animations.
This is supported, but it's kind of "hacky".
This feature is used extensively by [sweettea][] to make a more intuitive stylesheet DSL
Teacup is, by itself, pretty useful, but it really does little more than map
Hash keys to UIView setters. That's great, because it keeps the system easy
to understand. But there are some methods in UIKit that take more than one
argument, or could benefit from some shorthands.
This is where Teacup's style handlers come in. They are matched against a
UIView subclass and one or more stylenames, and they are used to apply that
style when you use it in your stylesheet.
# this handler adds a `:title` handler to the UIButton class (and subclasses).
Teacup.handler UIButton, :title do |target, title|
target.setTitle(title, forState: UIControlStateNormal)
end
# ...
subview(UIButton,
title: 'This is the title' # [[0, 0], superview.frame.size]These are super cool, just don't forget your autoresizingMasks
When positioning views you will often have situations where you want to have a
view centered, or 8 pixels to the right of center, or full width/height. All of
these relationships can be described using the Teacup.calculate method, which
is called automatically in any method that modifies the frame or center.
frame, origin, size
top/y, left/x, right, bottom, width, height
center_x/middle_x, center_y/middle_y, centerTeacup::Stylesheet.new :main do
style :button,
left: 8, top: 8, # easy enough!
width: '100% - 16', # woah! (O_o)
height: 22
style :top_half,
frame: [[0, 0], ['100%', '50%']]
style :bottom_half,
frame: [[0, '50%'], ['100%', '50%']]
endWhen this code executes, the string '100% - 16' is translated into the formula
1.00 * target.superview.frame.size.width - 16. If the property is related to
the height or y-position, it will be calculated based on the height.
The frame calculations must be a string of the form /[0-9]+% [+-] [0-9]+/. If
you need more "math-y-ness" than that, you can construct strings using interpolation.
margin = 8
style :button,
left: margin, top: margin,
width: "100% - #{margin * 2}",
height: 22
# just for fun, let's see what it would take to add a margin between these two views.
style :top_half,
frame: [[0, 0], ['100%', "50% - #{margin / 2}"]]
style :bottom_half,
frame: [[0, "50% + #{margin / 2}"], ['100%', "50% - #{margin / 2}"]]One more example: The real power of the frame calculations comes when you
remember to set springs and struts. You can have a view "pinned" to the bottom
if you remember to set the autoresizingMask.
Teacup::Stylesheet.new :main do
style :button,
# fixed width / height
height: 22, width: 200,
center_x: '50%',
top: '100% - 30', # includes an 8px margin from the bottom
autoresizingMask: (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin)
# see the autoresizing extension below for an even better way to write this.
endThis is another much bigger topic than it is given space for here
Teacup includes an Auto-Layout constraint DSL that you can use in your
stylesheets. These methods are added to the Stylesheet class, so unless you
are in the context of a stylesheet, you will have to create your constraints in
longhand (you can still use the Teacup::Constraint class to help you!).
I won't sugar-coat it: Auto-Layout is hard. Much harder than using frames and
springs and struts. And honestly, I recommend you try using the
Teacup.calculate features mentioned above, they will take you far.
But at the end of the day, once you really understand the auto-layout system that Apple released in iOS 6, you can build your UIs to be responsive to different devices, orientations, and sizes. UIs built with auto-layout not usually need to adjust anything during a rotation. The constraints take care of it all. It's impressive.
Here's a quick example that creates this shape. The edges are bound to the superview's frame.
+-----+----------------+
| | |
| A | B |
| | +-----| 20
vertical "|-[view_a]-margin-[view_b]-margin-[view_c]-|"
horizontal "|-margin-[view_a]-margin-|"
horizontal "|-margin-[view_b]-margin-|"
horizontal "|-margin-[view_c]-margin-|"
end end
### Stylesheet extensions
Auto-Layout is just one Stylesheet extension, there are a few others. And if
you want to write your own, just open up the `Teacup::Stylesheet` class and
start adding methods.
#### Autoresizing Masks
If you've used the SugarCube `uiautoresizingmask` methods, you'll recognize
these. They are handy, and hopefully intuitive, shorthands for common springs
and struts.
In previous versions of Teacup these were available without needing the
`autoresize` prefix. The old methods are still available, but deprecated.
```ruby
# keeps the width and heigNo open issues yet, or sync has not completed.