Sha256: a4d9ed6dd04a0edaa6556e8fef95b27415d52fabafebeab9487b4fd79ed24a30

Contents?: true

Size: 1.8 KB

Versions: 3

Compression:

Stored size: 1.8 KB

Contents

class UITextView
  attr_reader :placeholder
  attr_accessor :placeholder_color

  alias_method :old_initWithCoder, :initWithCoder
  def initWithCoder(decoder)
    old_initWithCoder(decoder)
    setup
    self
  end

  alias_method :old_initWithFrame, :initWithFrame
  def initWithFrame(frame)
    old_initWithFrame(frame)
    setup
    self
  end

  def setup
    @foreground_observer = NSNotificationCenter.defaultCenter.observe UITextViewTextDidChangeNotification do |notification|
      updateShouldDrawPlaceholder
    end
  end

  alias_method :old_dealloc, :dealloc
  def dealloc
    NSNotificationCenter.defaultCenter.unobserve @foreground_observer
    old_dealloc
  end

  alias_method :old_drawRect, :drawRect
  def drawRect(rect)
    old_drawRect(rect)

    if (@shouldDrawPlaceholder)
        self.placeholder_color.set
        self.placeholder.drawInRect(placeholder_rect, withFont:self.font)
    end
  end


  alias_method :old_setText, :setText
  def setText(text)
    old_setText(text)

    updateShouldDrawPlaceholder
  end

  def placeholder=(placeholder)
    return if @placeholder == placeholder

    @placeholder = placeholder

    updateShouldDrawPlaceholder
  end

  def placeholder_rect
    x_offset = font.xHeight
    y_offset = font.capHeight + font.descender

    CGRectMake(self.contentInset.left + x_offset, self.contentInset.top + y_offset, self.frame.size.width - self.contentInset.left - self.contentInset.right - x_offset, self.frame.size.height - self.contentInset.top - self.contentInset.bottom - y_offset)
  end

  def placeholder_color
    @placeholder_color ||= UIColor.lightGrayColor
  end

  def updateShouldDrawPlaceholder
    prev = @shouldDrawPlaceholder;
    @shouldDrawPlaceholder = self.placeholder && self.text.length == 0

    self.setNeedsDisplay if (prev != @shouldDrawPlaceholder)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
formotion-1.5.1 lib/formotion/patch/ui_text_view_placeholder.rb
formotion-1.5.0 lib/formotion/patch/ui_text_view_placeholder.rb
formotion-1.4.0 lib/formotion/patch/ui_text_view_placeholder.rb