iOS 6常用控件之UITextField

全代碼實現UITextField收鍵盤

之前,網上一個朋友問我如何直接使用代碼在一個自定義中的UIView中收鍵盤。糾結了一段時間後,想到了兩種方法。一種方式是在UIView上面添加一個UIControl,通過點擊屏幕收鍵盤,這種方式我覺得能稍微的簡單一點。另一種方法是實現UITextFieldDelegate協議中的方法,直點擊換行鍵(Return)收鍵盤。下面我就先說下比較簡單的。
(聲明我這個例子實在一個自定義的UIView中插入的UITextField對象,然後UIView將再viewController中,自定義的UIView類名爲 @class myView  )
第一種方法,


@interface myView : UIControl<UITextFieldDelegate>

//由於要實現UITextFieldDelegate中的-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

    UITextField * textfield;

}

@property(nonatomic,retain)UITextField * textfield;

@end


@synthesize textfield;

- (id)initWithFrame:(CGRect)frame

{

    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;

}


  1. <pre></pre>  
  2. <pre></pre>  
  1. <pre></pre>  
  2. <pre></pre>  
  3. <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的屏幕大小

 //點擊背景收鍵盤

        [uiCtrl addTarget: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];

}


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