簡體   English   中英

從一個類調用方法並在另一個類中使用

[英]Calling a Method from one class and used in another class

我在ViewController中有一個方法來繪制按鈕。 在ViewController2中,我想調用該方法並繪制按鈕。

在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

然后我試圖從ViewController2調用

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

NSLog顯示正確的文本,但未創建任何按鈕。 我怎么了

謝謝

使用可以從兩個視圖控制器調用的類方法創建一個單獨的類(例如,稱為Utils ):

@implementation Utils

+(void)methodForView:(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];
}

@end

並這樣稱呼它:

- (void)viewDidLoad {
    [super viewDidLoad];
    [Utils methodForView:self.view];
}

或者更好的方法是,在UIViewController -subclass中實現該方法,然后從該基類派生所有其他視圖控制器。

我認為這個問題是由“方法”上“自我”的范圍引起的。 您的按鈕已添加到defirstView中,而不是在secondView中。 要執行您想做的事情,您將必須傳遞想要添加按鈕的范圍。 就像@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 ");
}

在第二個視圖中,您可以調用:

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

我認為這就是問題,希望對您有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM