2011-05-30 157 views
11

在一個UITextView隱藏鍵盤,有方法:添加一個按鈕隱藏鍵盤

... 
    textfield.returnKeyType = UIReturnKeyDone; 
    textfield.delegate = self; 
.... 

-(BOOL)textFieldShouldReturn:(UITextField *)textField { 
    [textField resignFirstResponder]; 
    return YES; 

} 

,但如果我要離開按鈕「做」到「迴歸」,並添加一個按鈕隱藏鍵盤,我該怎麼辦?

回答

34

您可以指定一個工具欄,其中包含一個用於取消鍵盤的按鈕,即文本框的inputAccessoryView。一個簡單的例子是,

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:textField action:@selector(resignFirstResponder)] autorelease]; 
UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease]; 
toolbar.items = [NSArray arrayWithObject:barButton]; 

textField.inputAccessoryView = toolbar; 
+0

感謝,但如果我想也從一個密鑰的方法調用? – Vins 2011-05-30 19:40:24

+0

我沒有得到你。你想打甚麼? – 2011-05-30 19:49:44

+0

我有一個將文本保存到數據庫的方法[self saveString]; – Vins 2011-05-30 19:51:47

3

這可以做的更容易!

我在IB做了一個自定義視圖,在我viewController.h我只是做了一個IBOutlet UIView *accessoryView;,連接他們和- (IBAction)dismissKeyboard;

我把視圖中的工具欄與完成按鈕,做出了IBAction爲連接一個寫道: [textView resignFirstResponder]

- (void)viewDidLoad 
{ 
    textView.inputAccessoryView = accessoryView; 
    [super viewDidLoad]; 
} 

但實際上,看起來有點怪怪的和非蘋果風格的...有一個想法?

4

雨燕2.0的版本:

//Declared at top of view controller 
var accessoryDoneButton: UIBarButtonItem! 
let accessoryToolBar = UIToolbar(frame: CGRectMake(0,0,UIScreen.mainScreen().bounds.width, 44)) 
//Could also be an IBOutlet, I just happened to have it like this 
let codeInput = UITextField() 

//Configured in viewDidLoad() 
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.donePressed(_:))) 
self.accessoryToolBar.items = [self.accessoryDoneButton] 
self.codeInput.inputAccessoryView = self.accessoryToolBar 

斯威夫特4:

//Declared at top of view controller 
var accessoryDoneButton: UIBarButtonItem! 
let accessoryToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44)) 
//Could also be an IBOutlet, I just happened to have it like this 
let codeInput = UITextField() 

//Configured in viewDidLoad() 
self.accessoryDoneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.donePressed)) 
self.accessoryToolBar.items = [self.accessoryDoneButton] 
self.codeInput.inputAccessoryView = self.accessoryToolBar 

func donePressed() { 
    //Causes the view (or one of its embedded text fields) to resign the first responder status. 
    view.endEditing(true) 
} 

UIToolBar Documentation

'inputAccessoryView' documentation

+0

哪裏'donePressed'方法? – rmaddy 2017-03-26 17:32:38

+0

'donePressed'只是一個功能你' UIViewController'。我通常會辭去第一個響應者的活動鍵盤,然後如果我願意的話,將視圖控制器從導航棧中彈出。 – 2017-04-17 18:06:11