如何使用子类方法

时间:2012-04-28 07:57:05

标签: cocoa

我在课堂上有这个方法。我如何在我的子类(本类)中使用它,因为当我调用[self shiftViewUpForKeyboard]时;它需要参数,但是当我输入Notification时,它会给出错误。我知道这可能是非常基本的,但它会在我的整个应用程序中帮助我很多。

- (void) shiftViewUpForKeyboard: (NSNotification*) theNotification;
{


    CGRect keyboardFrame;
    NSDictionary* userInfo = theNotification.userInfo;
    keyboardSlideDuration = [[userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] floatValue];
    keyboardFrame = [[userInfo objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    UIInterfaceOrientation theStatusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];

    if UIInterfaceOrientationIsLandscape(theStatusBarOrientation)
        keyboardShiftAmount = keyboardFrame.size.width;
    else 
        keyboardShiftAmount = keyboardFrame.size.height;

    [UIView beginAnimations: @"ShiftUp" context: nil];
    [UIView setAnimationDuration: keyboardSlideDuration];
    self.view.center = CGPointMake( self.view.center.x, self.view.center.y - keyboardShiftAmount);
    [UIView commitAnimations];
    viewShiftedForKeyboard = TRUE;

}

谢天谢地!

1 个答案:

答案 0 :(得分:3)

这看起来像一个通知处理程序。您通常不应该自己调用通知处理程序。通知处理程序方法通常由NSNotificationCenter发出的通知调用。通知中心向处理程序方法发送NSNotification对象。在您的情况下,通知包括一些额外的用户信息。

您可以在代码中类似用户信息字典,该字典应直接调用处理程序并将其传递给处理程序方法(使用所需的用户信息字典构建您自己的NSNotification对象)。但是,这很容易出错,我认为这是一个“黑客”。

我建议您将代码放入一个不同的方法中,从问题中的通知处理程序中调用该方法,然后使用distinct方法进行直接调用。

然后你会:

- (void) shiftViewUpForKeyboard: (NSNotification*) theNotification;
{
    NSDictionary* userInfo = theNotification.userInfo;
    keyboardSlideDuration = [[userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] floatValue];
    keyboardFrame = [[userInfo objectForKey: UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    [self doSomethingWithSlideDuration:keyboardSlideDuration frame:keyboardFrame];
}

doSomethingWithSlideDuration:frame:方法实现为类的实例方法。在您直接调用它的代码中,请调用doSomethingWithSlideDuration:frame而不是调用通知处理程序。

直接调用方法时,您需要自己传递幻灯片持续时间和帧。

相关问题