#pragma mark 設置textView並在設置view隨鍵盤的移動而移動
-(void)setTextView
{
[self.myTextView.layer setCornerRadius:5.0];
//監聽鍵盤彈出
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
//監聽鍵盤消失
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden:) name:UIKeyboardWillHideNotification object:nil];
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
[topView setBarStyle:UIBarStyleBlackTranslucent];
//定義兩個flexibleSpace的button,放在toolBar上,這樣完成按鈕就會在最右邊
UIBarButtonItem * button1 =[[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * button2 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:self action:nil];
//定義完成按鈕
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(resignKeyboard)];
//在toolBar上加上這些按鈕
NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
[topView setItems:buttonsArray];
[self.myTextView setInputAccessoryView:topView];
}
#pragma mark 隱藏鍵盤
-(void)resignKeyboard
{ //取消鍵盤爲第一相應者
[self.myTextView resignFirstResponder];
}
#pragma mark 鍵盤彈出View向上移動
-(void)keyboardDidShow:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height; //獲取鍵盤高度
CGContextRef context = UIGraphicsGetCurrentContext();
//開始播放動畫
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3];
[self.myView setFrame:CGRectMake(0,-height, 320, 480)];
[UIView commitAnimations];
}
#pragma mark 鍵盤消失View向下移動
-(void)keyboardDidHidden:(NSNotification *)notification
{
CGContextRef context = UIGraphicsGetCurrentContext();
//開始播放動畫
[UIView beginAnimations:nil context:context];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3];
[self.myView setFrame:CGRectMake(0,0, 320, 480)];
[UIView commitAnimations];
}