-
Notifications
You must be signed in to change notification settings - Fork 103
/
ui_text_view_placeholder.rb
65 lines (50 loc) · 1.56 KB
/
ui_text_view_placeholder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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_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
CGRectMake(self.contentInset.left + 10.0, self.contentInset.top, self.frame.size.width - self.contentInset.left - self.contentInset.right - 16.0, self.frame.size.height - self.contentInset.top - self.contentInset.bottom - 16.0)
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