从一个类调用方法并在另一个类中使用 [英] Calling a Method from one class and used in another class

查看:119
本文介绍了从一个类调用方法并在另一个类中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ViewController中有一个方法来绘制一个按钮。在ViewController2中,我想调用该方法并绘制按钮。

I have the a method in ViewController to draw a button. In ViewController2 I want to call the method and draw the button out.

在ViewController.h中

In ViewController.h

@interface ViewController : UIViewController

-(void)method;
@end

ViewController.m

ViewController.m

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)method{
    UIButton*Touch1= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [Touch1 addTarget:self action:@selector(TouchButton1:) forControlEvents:UIControlEventTouchUpInside];
    [Touch1 setFrame:CGRectMake(50,50, 100, 100)];
    Touch1.translatesAutoresizingMaskIntoConstraints = YES;
    [Touch1 setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
    [Touch1 setExclusiveTouch:YES];
    [self.view addSubview:Touch1];

    NSLog(@"hi ");
}

-(void)TouchButton1:(UIButton*)sender{

    NSLog(@"hi again");

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

from ViewController2

Then I am trying to call from ViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    ViewController * ViewCon = [[ViewController alloc]init];
    [ViewCon method];
}

NSLog显示正确的文本,但没有创建按钮。
我的问题是什么?

The NSLog shows correct text but no button was created. What is my problem?

感谢

推荐答案

我认为这个问题是由范围的自我对方法方法。您的按钮已添加到de firstView中,而不是在secondView中。为了做你自己,你必须通过你喜欢的范围添加按钮。像@trojanfoe给出的示例。

i think this problem is caused by the scope of "self" on the method "method". Your button has been added into de firstView and not in the secondView. To do what you whant, you will have to pass the scope that you like to add the button. Like the sample given by @trojanfoe.

-(void)method:(UIView *)_view {
    UIButton*Touch1= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [Touch1 addTarget:self action:@selector(TouchButton1:) forControlEvents:UIControlEventTouchUpInside];
    [Touch1 setFrame:CGRectMake(50,50, 100, 100)];
    Touch1.translatesAutoresizingMaskIntoConstraints = YES;
    [Touch1 setBackgroundImage:[UIImage imageNamed:@"1.png"] forState:UIControlStateNormal];
    [Touch1 setExclusiveTouch:YES];
    [_view addSubview:Touch1];

    NSLog(@"hi ");
}

在第二个视图中,您可以调用:

And into your second view you can call:

 ViewController * ViewCon = [[ViewController alloc]init];
[ViewCon method:self.view];

我认为这是问题,我希望会帮助你

i think thats the problem, i hope that will help you

这篇关于从一个类调用方法并在另一个类中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆