#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
UIButton *doneInKeyboardButton;
}
- (IBAction)NOBut:(id)sender;
- (IBAction)But:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc {
//反注册通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
#pragma mark 键盘
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
if (doneInKeyboardButton.superview)
{
[doneInKeyboardButton removeFromSuperview];
}
}
- (void)handleKeyboardDidShow:(NSNotification *)notification
{
if (doneInKeyboardButton == nil)
{
doneInKeyboardButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
if(screenHeight==568.0f){//iphone5
doneInKeyboardButton.frame = CGRectMake(0, 568 - 53, 106, 53);
}else{//
doneInKeyboardButton.frame = CGRectMake(0, 480 - 53, 106, 53);
}
doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
//图片
[doneInKeyboardButton setImage:[UIImage imageNamed:@"btn_done_up@2x.png"] forState:UIControlStateNormal];
[doneInKeyboardButton setImage:[UIImage imageNamed:@"btn_done_down@2x.png"] forState:UIControlStateHighlighted];
[doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
}
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
if (doneInKeyboardButton.superview == nil)
{
[tempWindow addSubview:doneInKeyboardButton]; // 这里直接加到window上
}
}
-(void)finishAction{
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
}
#pragma mark textview
- (IBAction)But:(id)sender {
doneInKeyboardButton.hidden=YES;
}
- (IBAction)NOBut:(id)sender {
doneInKeyboardButton.hidden=NO;
}
@end