Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

ios - Calling a Method from one class and used in another class

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

In ViewController.h

@interface ViewController : UIViewController

-(void)method;
@end

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

Then I am trying to call from ViewController2

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

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...