ios - 用户输入文本字段的值后如何关闭键盘?

标签 ios objective-c

我知道这个问题已经被问过几次了,但是没有一个答案的细节足以让我 (me = n00b) 理解。

我有一个简单的小应用程序,我通过 Storyboard组合在一起,它有两个用户可以输入的文本字段。我希望用户在编辑任一字段后能够关闭键盘。

我知道它与“resignFirstResponder”有关,但我不确定该放在哪里。

这是我的绝密密码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize thing1;
@synthesize thing2;

// NSArray things = @[thing1, thing2];
// self.thingLabel.text = array[arc4random()%array.count];
- (IBAction)pick:(id)sender {
    // create an empty list that will get filled with things
    NSMutableArray *things = [NSMutableArray arrayWithObjects:thing1.text,thing2.text, nil];
    NSString *theThing = things[arc4random()%things.count];
    NSLog(@"the thing is %@", theThing);
}

@end

这是我的 ViewController.h 文件:

//


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *thing1;
@property (weak, nonatomic) IBOutlet UITextField *thing2;


@end

最佳答案

由于您的 View Controller 采用了 UITextFieldDelegate协议(protocol)(即 <UITextFieldDelegate> ),那么最简单的技术就是让 View Controller 实现以下两个方法:

// place in ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // note that you could set the text field delegate in IB instead
    self.thing1.delegate = self;
    self.thing2.delegate = self;
}

// this method gets called by the system automatically when the user taps the keyboard's "Done" button
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
    [theTextField resignFirstResponder];

    return YES;
}

这就是您需要的全部代码。现在,当用户点击键盘的“完成”按钮时,键盘就会消失。

关于ios - 用户输入文本字段的值后如何关闭键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20941036/

相关文章:

objective-c - 正确使用 Objective C++

ios - 使用 Objective C 进行图像混合

ios - 从 iOS 中的气压计访问压力值

ios - 当每次向 iOS 中的文本字段添加三个数字时,为整数插入一个逗号

iphone - 选择时动画 UITableViewCell 高度

iphone - iOS 中的日历计算在 1577 年之前就中断了...(朱利安-> 公历)

ios - Swift 问题 - NSUserDefault 和设置包没有响应

ios - 如何在它继续之前添加延迟

objective-c - NSFetchedResultsController 返回错误的 NSFetchedResultsChangeType

Objective-C 和 NSURL : where am I supposed to declare receivedData?