读书人

给iphone的键盘加下UITextField

发布时间: 2012-08-30 09:55:54 作者: rapoo

给iphone的键盘加上UITextField
原文地址:给键盘加上UITextField
http://www.aisidechina.com/forum/viewthread.php?tid=914
效果:


.h文件:

#import <UIKit/UIKit.h>@interface ScoreBar : UIToolbar {UITextField *nameTextField;UILabel *scoreLabel;}@property (nonatomic, retain) UITextField *nameTextField; //toolbar上的输入框@property (nonatomic, retain) UILabel *scoreLabel; //toolbar上的按钮-(void)keyboareWillShow:(NSNotification*)aNotification; //键盘将要出现时调用@end
.m文件
#import "ScoreBar.h"@implementation ScoreBar@synthesize nameTextField;@synthesize scoreLabel;- (id)initWithFrame:(CGRect)frame {    if (self = [super initWithFrame:frame]) {        // Initialization codeself.hidden = YES;self.tintColor = [UIColor grayColor];               /*                 初始化toolbar上的textField和button               */......略/*                 设定UIKeyboardWillShowNotification调用的方法              */[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(keyboareWillShow:) name:UIKeyboardWillShowNotification    object:nil];    }    return self;}- (void)drawRect:(CGRect)rect {[super drawRect:rect];//调用父类的方法,这个一定要写    // Drawing code}- (void)dealloc {      .......}-(void)keyboareWillShow:(NSNotification*)aNotification{        /* 取得键盘的frame */NSDictionary *info = [aNotification userInfo];NSValue *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];CGRect frame;[aValue getValue:&frame];        //设定toolbar的frame        self.frame = CGRectMake(frame.origin.x, frame.origin.y-44, frame.size.width, 44);UIWindow *tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];UIView *keyboard;/*遍历windwos中所有的view,取得键盘view*/for(int i = 0;i<tempWindow.subviews.count;i++){keyboard = [tempWindow.subviews objectAtIndex:i];if([[NSString stringWithUTF8String:object_getClassName(keyboard)] isEqualToString:@"UIKeyboard"]){self.hidden = NO;[keyboard addSubview:self];[keyboard setBackgroundColor:[UIColor blackColor]];}}}@end
初始化toolbar:
ScoreBar *scoreBar = [[ScoreBar alloc] initWithFrame:CGRectMake(0, 0, 480, 44)];scoreBar.nameTextField.delegate = self;
使用becomeFirstResponder调出键盘:
[scoreToolBar.nameTextField becomeFirstResponder];

读书人网 >Iphone

热点推荐