2013-04-25 148 views
0

我正在构建基于标记的应用程序,并且想要从每个选项卡调用相同的函数(ViewController)。无法调用类方法

我试图做下列方式:

#import "optionsMenu.h" 

- (IBAction) optionsButton:(id)sender{ 
    UIView *optionsView = [options showOptions:4]; 
    NSLog(@"options view tag %d", optionsView.tag); 
} 

optionsMenu.h文件:

#import <UIKit/UIKit.h> 

@interface optionsMenu : UIView 

- (UIView*) showOptions: (NSInteger) tabNumber; 

@end 

optionsMenu.m文件:

@import "optionsMenu.h" 
@implementation optionsMenu 

- (UIView*) showOptions:(NSInteger) tabNumber{ 
    NSLog(@"show options called"); 

    UIView* optionsView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    optionsView.opaque = NO; 
    optionsView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f]; 
    //creating several buttons on optionsView 
    optionsView.tag = 100; 

return optionsView; 

} 

@end 

的结果是,我从来没有“show options called”调试消息,因此optionsView.tag是alwa ys 0

我在做什么错了?

我知道这很可能是一个容易和愚蠢的问题,但我无法自己解决它。

任何反馈意见。

+0

我猜这是Objective-C。下次,请用适当的语言标记您的问题。 – 2013-04-25 10:22:08

+0

'options'是否正确初始化? – 2013-04-25 10:25:38

+0

刚宣布为optionsMenu * options; – 2013-04-25 10:27:16

回答

3

首先要注意的是,这是一个实例方法(而不是问题标题中描述的Class方法)。这意味着为了调用这个方法,你应该为你的Class分配/ init一个实例并且把消息发送给实例。例如:现在

// Also note here that Class names (by convention) begin with 
// an uppercase letter, so OptionsMenu should be preffered 
optionsMenu *options = [[optionsMenu alloc] init]; 
UIView *optionsView = [options showOptions:4]; 

,如果你只是想创建一个返回一个预配置的UIView一个类的方法,你可以尝试这样的事情(前提是你并不需要在你的方法获得高德):

// In your header file 
+ (UIView *)showOptions:(NSInteger)tabNumber; 

// In your implementation file 
+ (UIView *)showOptions:(NSInteger)tabNumber{ 
    NSLog(@"show options called"); 

    UIView *optionsView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    optionsView.opaque = NO; 
    optionsView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5f]; 
    //creating several buttons on optionsView 
    optionsView.tag = 100; 

    return optionsView; 
} 

最后发送这样的信息:

UIView *optionsView = [optionsMenu showOptions:4]; //Sending message to Class here 

最后不要忘了,当然添加视图作为一个子视图,以显示它。 我希望这是有道理的...

+0

现在完美。非常感谢! – 2013-04-25 10:46:39