#import "SANumberKeyboard.h"
@implementation
SANumberKeyboard
+ (instancetype)keyboardWithTextField:(SATextField *)textField;
{
SANumberKeyboard *keyboard = [[
self
alloc] init];
keyboard.textField = textField;
return
keyboard;
}
- (instancetype)init
{
self
= [[[
NSBundle
mainBundle] loadNibNamed:
@"SANumberKeyboard"
owner:
nil
options:
nil
] firstObject];
for
(UIButton *btn in
self
.subviews) {
if
(btn.tag == 0)
continue
;
UIImage *image = [
self
imageWithColor:[UIColor whiteColor]];
UIImage *image1 = [
self
imageWithColor:[UIColor colorWithWhite:0.8 alpha:1.0]];
if
(btn.tag <= 10)[btn setBackgroundImage:image forState:UIControlStateNormal];
if
(btn.tag > 10)[btn setBackgroundImage:image1 forState:UIControlStateNormal];
[btn addTarget:
self
action:
@selector
(buttonEven:) forControlEvents:UIControlEventTouchUpInside];
}
return
self
;
}
- (UIImage *)imageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return
image;
}
- (
void
)buttonEven:(UIButton *)button
{
UITextRange *textRange =
self
.textField.selectedTextRange;
NSString
*string =
@""
;
switch
(button.tag) {
case
1: string =
@"1"
;
break
;
case
2: string =
@"2"
;
break
;
case
3: string =
@"3"
;
break
;
case
4: string =
@"4"
;
break
;
case
5: string =
@"5"
;
break
;
case
6: string =
@"6"
;
break
;
case
7: string =
@"7"
;
break
;
case
8: string =
@"8"
;
break
;
case
9: string =
@"9"
;
break
;
case
10: string =
@"0"
;
break
;
case
11: string =
@"."
;
break
;
case
12:{
if
(textRange.isEmpty){
UITextPosition *from = [
self
.textField positionFromPosition:textRange.start offset:-1];
UITextPosition *to = [
self
.textField positionFromPosition:textRange.start offset:0];
textRange = [
self
.textField textRangeFromPosition:from toPosition:to];
}
}
break
;
default
:
break
;
}
[
self
.textField replaceRange:textRange withText:string];
}
@end