class UILabel

Public Class Methods

label(text=nil, font=nil, size=nil) click to toggle source

@example

UILabel.label('test')
UILabel.label('test', another_label.font)
UILabel.label('test', 'Helvetica')
UILabel.label('test', 'Helvetica', 20)
# File lib/ios/sugarcube-factories/uilabel.rb, line 8
def self.label(text=nil, font=nil, size=nil)
  return new() if text.nil?

  font = font.uifont(size) if font.respond_to?(:uifont)
  label = self.alloc.initWithFrame([[0, 0], [0, 0]])
  if text.is_a?(NSAttributedString)
    label.attributedText = text
  else
    label.text = text
  end
  if font
    label.font = font
  end
  label.backgroundColor = :clear.uicolor
  label.sizeToFit
  label
end

Public Instance Methods

fit_to_size(max_size) click to toggle source

forces the given text to fit inside the label's frame starting at a given font size

# File lib/ios/sugarcube-ui/uilabel.rb, line 4
def fit_to_size(max_size)
  #enforce word wrap
  self.lineBreakMode = NSLineBreakByWordWrapping

  dynamic_font = self.font.fontWithSize(max_size + 2)
  constraintSize = CGSizeMake(self.frame.size.width, 10000)

  # does it fit yet?
  begin
    dynamic_font = dynamic_font.fontWithSize(dynamic_font.pointSize - 2)
    current_size = self.text.sizeWithFont(dynamic_font, constrainedToSize:constraintSize, lineBreakMode: NSLineBreakByWordWrapping)
  end while self.frame.size.height <= current_size.height

  #now set to font size we have settled on
  self.font = dynamic_font

end
sugarcube_to_s(options={}) click to toggle source
Calls superclass method
# File lib/ios/sugarcube-to_s/uilabel.rb, line 3
def sugarcube_to_s(options={})
  text = self.text
  if text && text.length > 20
    text = text[0..20] + '...'
  end
  super options.merge(inner: {text: text})
end