Class: MotionPrime::ViewStyler

Inherits:
Object
  • Object
show all
Includes:
ElementTextMixin, FrameCalculatorMixin, HasClassFactory, HasStyles
Defined in:
motion-prime/views/view_styler.rb

Constant Summary collapse

STRUCTS_MAP =
{
  CGAffineTransform   => Proc.new {|v| NSValue.valueWithCGAffineTransform(v) },
  CGPoint             => Proc.new {|v| NSValue.valueWithCGPoint(v) },
  CGRect              => Proc.new {|v| NSValue.valueWithCGRect(v) },
  CGSize              => Proc.new {|v| NSValue.valueWithCGSize(v) },
  UIEdgeInsets        => Proc.new {|v| NSValue.valueWithUIEdgeInsets(v) },
  UIOffset            => Proc.new {|v| NSValue.valueWithUIOffset(v) }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ElementTextMixin

#attributed_string, #extract_attributed_string_options, #html_string

Methods included from HasClassFactory

#camelize_factory, #class_factory, #low_camelize_factory

Methods included from HasStyles

#prepare_gradient

Methods included from FrameCalculatorMixin

#calculate_frome_for

Constructor Details

#initialize(view, bounds = CGRectZero, options = {}) ⇒ ViewStyler

Returns a new instance of ViewStyler.



10
11
12
13
14
15
# File 'motion-prime/views/view_styler.rb', line 10

def initialize(view, bounds = CGRectZero, options = {})
  @options = Styles.extend_and_normalize_options options
  @view = view
  prepare_frame_for(bounds) if @options.delete(:calculate_frame)
  prepare_options!
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'motion-prime/views/view_styler.rb', line 8

def options
  @options
end

#viewObject (readonly)

Returns the value of attribute view.



8
9
10
# File 'motion-prime/views/view_styler.rb', line 8

def view
  @view
end

Instance Method Details

#applyObject



17
18
19
20
21
22
# File 'motion-prime/views/view_styler.rb', line 17

def apply
  converted_options = convert_primitives_to_objects(options)
  converted_options.each do |key, value|
    set_option(key.to_s, value)
  end
end

#convert_primitives_to_objects(options) ⇒ Object



24
25
26
27
28
29
30
# File 'motion-prime/views/view_styler.rb', line 24

def convert_primitives_to_objects(options)
  options.inject({}) do |result, (k, v)|
    v = STRUCTS_MAP[v.class].call(v) if STRUCTS_MAP.has_key?(v.class)
    result[k] = v
    result
  end
end

#extract_attributed_text_options(options) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'motion-prime/views/view_styler.rb', line 74

def extract_attributed_text_options(options)
  text_attributes = [
    :text, :html, :line_spacing, :line_height, :underline, :fragment_color,
    :text_alignment, :font, :line_break_mode, :number_of_lines
  ]
  attributed_text_options = options.slice(*text_attributes)
  options.except!(*text_attributes)
  attributed_text_options
end

#extract_font_options(options, prefix = nil) ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'motion-prime/views/view_styler.rb', line 63

def extract_font_options(options, prefix = nil)
  key = [prefix, 'font'].compact.join('_').to_sym
  name_key = [prefix, 'font_name'].compact.join('_').to_sym
  size_key = [prefix, 'font_size'].compact.join('_').to_sym
  if options.slice(size_key, name_key).any?
    font_name = options.delete(name_key) || :system
    font_size = options.delete(size_key) || 14
    options[key] ||= font_name.uifont(font_size)
  end
end

#prepare_frame_for(bounds) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'motion-prime/views/view_styler.rb', line 32

def prepare_frame_for(bounds)
  options[:frame] = calculate_frome_for(bounds, options.merge(test: view.is_a?(UITextView)))
  if options.slice(:width, :height, :right, :bottom, :height_to_fit).values.any?
    mask = UIViewAutoresizingNone
    mask |= UIViewAutoresizingFlexibleTopMargin if options[:top].nil?
    mask |= UIViewAutoresizingFlexibleLeftMargin if options[:left].nil?
    mask |= UIViewAutoresizingFlexibleBottomMargin if options[:bottom].nil?
    mask |= UIViewAutoresizingFlexibleRightMargin if options[:right].nil?
    mask |= UIViewAutoresizingFlexibleWidth if !options[:left].nil? && !options[:right].nil?
    mask |= UIViewAutoresizingFlexibleHeight if options[:height_to_fit].nil? && (!options[:top].nil? && !options[:bottom].nil?)
    options[:autoresizingMask] = mask
  end
end

#prepare_options!Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'motion-prime/views/view_styler.rb', line 46

def prepare_options!
  if options.slice(:html, :line_spacing, :line_height, :underline, :fragment_color).any?
    text_options = extract_attributed_text_options(options)

    html = text_options.delete(:html)
    text_options[:text] = html if html
    options[:attributed_text] = html ? html_string(text_options) : attributed_string(text_options)

    # ios 7 bug fix when text is invisible
    if text_options.slice(:line_height, :line_spacing, :text_alignment, :line_break_mode).any? && options.fetch(:number_of_lines, 1) == 1
      options[:number_of_lines] = 0
    end
  end
  extract_font_options(options)
  extract_font_options(options, 'placeholder')
end

#set_option(key, value) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'motion-prime/views/view_styler.rb', line 84

def set_option(key, value)
  # return if value.nil?
  # ignore options
  return if key == 'section' && !view.respond_to?(:section=)
  return if key == 'size_to_fit' && view.is_a?(UILabel)
  return if %w[url default draw_in_rect].include?(key.to_s) && view.is_a?(UIImageView)
  return if %w[
    styles has_drawn_content
    width height top right bottom left value_type
    max_width max_outer_width min_width min_outer_width
    max_height max_outer_height min_height min_outer_width
    height_to_fit container parent_frame].include? key.to_s

  # apply options
  if key.end_with?('title_color')
    view.setTitleColor value.uicolor, forState: UIControlStateNormal
  elsif key.end_with?('alignment') && value.is_a?(Symbol)
    view.setValue value.uitextalignment, forKey: camelize_factory(key)
  elsif key.end_with?('line_break_mode') && value.is_a?(Symbol)
    view.setValue value.uilinebreakmode, forKey: camelize_factory(key)
  elsif key.end_with?('title_shadow_color')
    view.setTitleShadowColor value.uicolor, forState: UIControlStateNormal
  elsif key.end_with?('color')
    color = value.try(:uicolor)
    color = color.cgcolor if view.is_a?(CALayer)
    view.send :"#{low_camelize_factory(key)}=", color
  elsif key.end_with?('background_image')
    if view.is_a?(UIButton)
      view.setBackgroundImage value.uiimage, forState: UIControlStateNormal
    elsif view.is_a?(UISearchBar) && key == 'search_field_background_image'
      view.setSearchFieldBackgroundImage value.uiimage, forState: UIControlStateNormal
    else
      view.setBackgroundColor value.uiimage.uicolor
    end
  elsif key.end_with?('background_view')
    if view.is_a?(UITableView)
      bg_view = UIView.alloc.initWithFrame(view.bounds)
      bg_view.backgroundColor = value[:color].uicolor
      view.backgroundView = bg_view
    else
      view.setValue value, forKey: low_camelize_factory(key)
    end
  elsif key.end_with?('image')
    view.setValue value.uiimage, forKey: camelize_factory(key)
  elsif key.end_with?('_content_inset')
    current_inset = view.contentInset
    current_inset.send("#{key.partition('_').first}=", value)
    view.contentInset = current_inset
  elsif key == 'autocapitalization'
    view.autocapitalizationType = UITextAutocapitalizationTypeNone if value === false
  elsif key == 'keyboard_type'
    view.setKeyboardType value.uikeyboardtype
  elsif key == 'rounded_corners'
    radius = value[:radius].to_f
    corner_consts = {top_left: UIRectCornerTopLeft, bottom_left: UIRectCornerBottomLeft, bottom_right: UIRectCornerBottomRight, top_right: UIRectCornerTopRight}
    corners = value[:corners].inject(0) { |result, corner| result|corner_consts[corner] }
    size = options[:parent_frame].size
    bounds = CGRectMake(0, 0, size.width, size.height)
    mask_path = UIBezierPath.bezierPathWithRoundedRect(bounds, byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius))
    mask_layer = CAShapeLayer.layer
    mask_layer.frame = bounds
    mask_layer.path = mask_path.CGPath
    view.mask = mask_layer
  elsif key == 'attributed_text'
    if view.is_a?(UIButton)
      view.setAttributedTitle value, forState: UIControlStateNormal
    else
      view.attributedText = value
    end
  elsif key == 'gradient'
    gradient = prepare_gradient(value)
    view.layer.insertSublayer(gradient, atIndex: 0)
  elsif key == 'selection_style' && view.is_a?(UITableViewCell) && value.is_a?(Symbol)
    view.setSelectionStyle value.uitablecellselectionstyle
  elsif key == 'estimated_cell_height' && view.is_a?(UITableView)
    view.setEstimatedRowHeight value
  elsif key == 'separator_inset' && (view.is_a?(UITableViewCell) || view.is_a?(UITableView))
    if value.to_s == 'none'
      view.separatorInset = UIEdgeInsetsMake(0, 320, 0, 0)
    elsif value.is_a?(Array) && value.count == 2
      view.separatorInset = UIEdgeInsetsMake(0, value.first, 0, value.last)
    end
  elsif value.is_a?(Hash)
    self.class.new(view.send(low_camelize_factory(key).to_sym), nil, value.merge(parent_frame: options[:frame] || options[:parent_frame])).apply
  else
    view.setValue value, forKey: low_camelize_factory(key)
  end
end