2012-02-23 65 views
1

我有以下代碼:Objective-C的重構方法

-(void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField]; 
CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view]; 
... 

} 

正如你可以看到它在傳遞一個的UITextField。我也有這個代碼重複在同一個ViewController中,但傳入一個UITextView。

我想能夠重構成一個單一的方法,通過UITextField或UITextView?我怎樣才能做到這一點?

此代碼也出現在其他視圖控制器中,所以理想情況下我希望將它放在助手類中,對於iOS來說非常新,所以不確定從哪裏開始。

爲了簡潔起見,我已經從該方法中刪除了大部分代碼,但它所做的是在出現iOS鍵盤時將UI控件滑入視圖中。

回答

4

您可以期待UIView,因爲您似乎沒有從這些視圖中使用任何特殊的文本屬性。

-(void)textFieldDidBeginEditing:(UIView *)textField 
{ 
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField]; 
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view]; 
    // ... 
} 
3

調用助手方法,這需要一個UIView,即普通超類。

-(void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    return [self textBeginEditing:textField]; 
} 


-(void)textViewDidBeginEditing:(UITextView *)textView 
{ 
    return [self textBeginEditing:textView]; 
} 


-(void)textBeginEditing:(UIView *)view 
{ 
    //and if you need to do something, where you need to now, if it is a textView or a field, use 

    if([view isKindOfClass:[UITextField class]]){ 
     //… 
    } else if([view isKindOfClass:[UITextView class]]){ 
     //… 
    } 
}