如何在类中调用另一个类写在.M中的方法

2016-04-21  本文已影响0人  wu2016

如何在类中调用另一个类写在.m中的方法,这种事情不常见,因为一般情况下如果我们在外界需要用到这个类的方法的时候我们会在.h中先声明这个方法。
但是如果我们用的别人的第三方库,当我们需要用到别人库中写在.m里的方法而又不想改动别人库的时候就需要用到了。这里举个简单的例子:

在ViewController中添加一个方法changeBackgroundColor用来改变视图颜色:

#import "ViewController.h"
#import "AppDelegate.h"
#import "FirstViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加一个导航控制器
    UINavigationController *NC = [[UINavigationController alloc] initWithRootViewController:self];
    ((AppDelegate *)[UIApplication sharedApplication].delegate).window.rootViewController = NC;
    self.view.backgroundColor = [UIColor redColor];
}

//在触摸屏幕的时候跳到另一页面
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    FirstViewController *firstV = [[FirstViewController alloc] init];
    [self.navigationController pushViewController:firstV animated:YES];
}

- (void)changeBackgroundColor
{
    self.view.backgroundColor = [UIColor yellowColor];
}

@end

在FirstViewController中添加一个按钮,在点击按钮的时候调ViewController中的changeBackgroundColor方法,使ViewController改变视图颜色

#import "FirstViewController.h"

//去除警告
#define PerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)

@implementation FirstViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 100, 50);
    [button setTitle:@"变色" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor blueColor];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(didClickBtn) forControlEvents:UIControlEventTouchUpInside];
}

//按钮的点击事件
- (void)didClickBtn
{
    SEL sel=NSSelectorFromString(@"changeBackgroundColor");
    PerformSelectorLeakWarning(
                               [[self.navigationController.childViewControllers firstObject]  performSelector:sel withObject:nil]);
    [self.navigationController popViewControllerAnimated:YES];
}
@end

Demo在这里

上一篇 下一篇

猜你喜欢

热点阅读