百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

teacup

> 编程语言
开源

此项目已被取消,以便支持 MotionKit

599 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

此项目已被取消,以便支持 MotionKit

Teacup

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.

A note about Teacup and MotionKit

Read a letter from Colin T.A. Gray regarding the future of Teacup and introducing MotionKit, its successor.

Check out some sample apps!

  • iOS
    • Hai
    • AutoLayout
    • Sweettea Example
  • OS X
    • Tweets - ported from RubyMotionSamples
    • simple

Quick Install

bash
> gem install teacup

and in your Rakefile

ruby
require 'teacup'

10 second primer, iOS

  1. Create a 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.

app_delegate.rb
ruby
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

end

That 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.

Now go use Teacup!

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!

Teacup as a utility

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.

…

UITableViews

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.

ruby
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
end

Constraints and styles get applied before the view appears, even if the cell is reused later.

More Teacup features

There are a few (OK, a bunch) more features that Teacup provides that deserve discussion:

  • Styling View Properties
  • Orientation Styles
  • View Class Additions
  • Style Handlers
  • Frame Calculations
  • Auto-Layout & [Motion-Layout][motion-layout]
  • Stylesheet Extensions

Styling View Properties

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!

ruby
# 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
  }

Orientation Styles

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.

ruby
Teacup::Stylesheet.new :main do

  # this label hides when the orientation is landscape (left or right)
  style :label,
    landscape: {
      hidden: true
    },
    portrait: {
      hidden: false
    }

end

Combine these styles with [Frame Calculations][calculations] to have you view frame recalculated automatically.

Animation additions

We've already seen the Teacup related properties:

  • stylename, the primary style name
  • style_classes, secondary style names
  • style, apply styles directly

Each 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".

Style Handlers

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.

ruby
# 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]

Frame Calculations

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, center
ruby
Teacup::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%']]

end

When 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.

ruby
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.

ruby
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.
end

Auto-Layout

This 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 heig

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言