【发布时间】:2013-09-16 07:36:39
【问题描述】:
我以编程方式创建了一个UITextField,使UITextField 成为viewController 的一个属性。我需要通过返回和触摸屏幕来关闭键盘。我能够让屏幕触摸消失,但按回车键不起作用。
我已经了解了如何使用情节提要以及直接分配和初始化 UITextField 对象而不将其创建为属性。可以吗?
.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, atomic) UITextField *username;
@end
.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
self.username.placeholder = @"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
_username.delegate = self;
[self.view addSubview:self.username];
[_username resignFirstResponder];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
@end
【问题讨论】:
标签: ios keyboard uitextfield