iOS中鍵盤隱藏幾種方式

來源:互聯網
上載者:User

標籤:

轉載學習http://www.cnblogs.com/jerehedu/p/4496421.html

在ios開發中,經常需要輸入資訊。輸入資訊有兩種方式: UITextField和UITextView。資訊輸入完成後,需要隱藏鍵盤,下面為大家介紹幾種隱藏鍵盤的方式。

<一> 點擊鍵盤上的return按鈕,隱藏鍵盤

  1、UITextField

  遵守協議

@interface ViewController ()<UITextFieldDelegate>

      設定代理

myTextfield.delegate=self;

使用代理中的方法

-(BOOL)textFieldShouldReturn:(UITextfield *)textField

{

[myTextField resignFirstRespinder];

return NO;

}

2、UITextView

  遵守協議

@interface ViewController ()<UITextViewDelegate>

設定代理

textView.delegate=self;

使用代理中的方法:

-(BOOL)textView:(UITextview *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

if([text [email protected]"\n"]){

[textView resignFirstResponder];

return NO;

}

return YES;

}

<二> 在鍵盤上添加一個按鈕,點擊按鈕隱藏鍵盤

  設定按鈕

UIToolbar *topView=[[UIToolbar alloc]initWithFrame:CGRectMake(0,0,320,30)];

[topView setBarStyle:UIBarStyleBlack];

UIBarButtoItem *btnSpace=[[UIBarButtonItem alloc]initWihBarButtonSystemItem:

UIBarButtonSystemItemFlexibleSpace target:self action:nil];

UIBarButtonItem *doneButton=[[UIBarButtonItem alloc]initWithTitle:@"完成" style:

UIBarButtonItemStyleDone tsrget :self action: @swelector(dismissKeyBoard)];

NSArrar * buttonArray=[NSArrar arrayWithPbjects:btnSpace,doneButton,nil];

[topView setItems:buttonArray];

1、UITextField

[myTextField setInputAccessoryView:TopView];

2、UITExtView

[textView setInputAccessoryView:topView];

添加隱藏鍵盤方法

-(void)dismissKeyBoar

{

[myTextField resignFirstResponder];

[textView resignFirstResponder];

}

<三>點擊除鍵盤以外的空白位置讓鍵盤隱藏。

  在touchesBegan:withEvent:方法中讓輸入控制項放棄第一響應者身份

-(void)touchesBegan:(NSString *)touches withEvent:(UIEvent *)event{

[myTextField resignFirstResponder];

[textView resignFirstReponder];

}

<四> 添加手勢,單擊除鍵盤以外的空白位置讓鍵盤隱藏

 //添加單擊手勢

UITapGuestureRecognizer *tap=[[UITapGuestureRecognizer alloc]initWithTarget:self action:@selector(dismissKeyBoard)];

tap.numberOfTouchedRequired=1;

tap.numberOfTapsRequired=1;

[self.view addGestureRecgnizer:tap];

//隱藏鍵盤

-(void)dismissKeyBoard{

[myTextField resigFirstRespinder];

[textView resigFirstRespinder];

}

<五> 只要點擊除鍵盤以外的空白介面,無論是點擊哪個控制項彈出的鍵盤,鍵盤都隱藏

-(void)touchhesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[self.view endEditing:YES];

}

iOS中鍵盤隱藏幾種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.