从一个类调用Method并在另一个类中使用
我有一个ViewController中的方法来绘制一个button。 在ViewController2中,我想调用方法并绘制button。
在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显示正确的文本,但没有创buildbutton。 我的问题是什么?
谢谢
我认为这个问题是由方法“方法”上“自我”的范围造成的。 您的button已添加到firstView中,而不是在第二个视图中。 要做你想做的事情,你必须通过你想添加button的范围。 就像@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];
我认为这是问题,我希望这会帮助你
用一个可以从两个视图控制器中调用的类方法创build一个单独的类(例如称为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中实现该方法,然后从这个基类派生所有其他视图控制器。