關於鍵盤上方創建返回按鈕

鍵盤在模式下,可能沒有返回或者是完成按鈕,因此有的時候需要人爲的添加一個返回或者是完成按鈕。

首先,創建一個工程:

@interface ViewController ()<UITextFieldDelegate>
{
    UITextField *testField;
}
@end

創建一個全局的,方便調用

在自己想要調用的方法中創建textField

- (void)viewDidLoad {
    [super viewDidLoad];
   
    testField =[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
    [self.view addSubview:testField];
    testField.placeholder = @"搜索內容";
    
    
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleBlackTranslucent];
    
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(2, 5, 50, 25);
    [btn addTarget:self action:@selector(dismissKeyBoard) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"完成" forState:UIControlStateNormal];
//    [btn setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithCustomView:btn];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneBtn,nil];
    [topView setItems:buttonsArray];
    [testField setInputAccessoryView:topView];

    
    
}
-(void)dismissKeyBoard
{
    [testField resignFirstResponder];
}

這樣一個簡單的鍵盤迴收demo就完成的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章