以前,网上一个朋友问我如何直接使用代码在一个自定义中的UIView中收键盘。纠结了一段时间后,想到了两种方法。一种方式是在UIView上面添加一个UIControl,经过点击屏幕收键盘,这种方式我以为能稍微的简单一点。另外一种方法是实现UITextFieldDelegate协议中的方法,直点击换行键(Return)收键盘。下面我就先说下比较简单的。(声明我这个例子实在一个自定义的UIView中插入的UITextField对象,而后UIView将再viewController中,自定义的UIView类名为 @class myView )第一种方法,
@interface myView : UIControl<UITextFieldDelegate> ios
//因为要实现UITextFieldDelegate中的-(BOOL)textFieldShouldReturn:(UITextField *)textField app
{ ide
UITextField * textfield; ui
} atom
@property(nonatomic,retain)UITextField * textfield; spa
@end .net
@synthesize textfield; code
- (id)initWithFrame:(CGRect)frame 对象
{ blog
self = [superinitWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor=[UIColorwhiteColor];
textfield=[[UITextFieldalloc]initWithFrame:CGRectMake(40,50,150,30)];
textfield.delegate=self;//因为textfield须要一个对象实现本身协议中的方法,因此委托给当前这个myView的类来实现协议中的方法
[textfieldsetBackgroundColor:[UIColorgrayColor]];
[self addSubview:textfield];
}
return self;
}
#pragma mark deal with textFieldDelegate & 收键盘处理
- (BOOL)textFieldShouldReturn:(UITextField *)textField//这个就是以前说的那个协议方法,只要调用了这个方法就能实现收键盘了
{
[textField resignFirstResponder];
return YES;
}
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
下面是第二种发法。在UIView中直接添加一个与屏幕等大小的UIControl对象,而后为这个UIControl对象实现简单点击事件。
这里仍是引用以前的那段代码- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
// 第二种方法------add by Grozy
UIControl * uiCtrl=[[UIControlalloc]initWithFrame:CGRectMake(0,0,320,640)];// 320 和 640是ios的屏幕大小
//点击背景收键盘
[uiCtrladdTarget:selfaction:@selector(tapBackground)forControlEvents:UIControlEventTouchUpInside];
[selfaddSubview:uiCtrl];
// 第二种方法 --------end
self.backgroundColor=[UIColorwhiteColor];
textfield=[[UITextFieldalloc]initWithFrame:CGRectMake(40,50,150,30)];
textfield.delegate=self;//因为textfield须要一个对象实现本身协议中的方法,因此委托给当前这个myView的类来实现协议中的方法
[textfieldsetBackgroundColor:[UIColorgrayColor]];//若是不设置会看不见的
[self addSubview:textfield];
}
return self;
}
-(void)tapBackground
{[self.textfieldresignFirstResponder];
}