2012-02-23 66 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]]){ 
     //… 
    } 
}