[英]Calling a method of One View controller from Another View Controller
我在OneViewController.h中声明了一个方法“someMethod”
@interface OneViewController
{
UIView *tempView;
..
}
-(void) someMethod ;
@end
并在OneViewController.m文件中实现
@implementation OneViewController
-(void) someMethod
{
tempView = [[UIView alloc]initWithFrame:CGRectMake(100, 50, 200, 250)];
tempView.backgroundColor = [UIColor yellowColor];
if([[self.view subviews] containsObject:tempView])
[tempView removeFromSuperView];
else
[self.view addsubview:tempView];
}
我想在不同的viewController - secondViewController中调用someMethod
(类似于[OneViewController someMethod]
),所以当我回到OneViewController时,我可以看到someMethod所做的更改。
我需要使用appDelegate方法吗?
我试过跟随,但它不起作用。
neViewController *newViewController = [[OneViewController alloc] init];
[newViewController someMethod];
在此先感谢您的帮助..
在SecondViewController中,声明OneViewController类的引用。 您可以指定属性。 在移动到SecondViewController之前设置引用。 现在有了引用,你可以调用实例方法[_oneView someMethod]
。
编辑:
宣布
OneViewController *_oneView;
还要添加assign属性,
@property(nonatomic,assign) OneViewController *_oneView;
合成.m文件中的变量。
在从OneViewController显示SecondViewController时,只需添加以下行。
secondView._oneView = self;
有时调用创建[classObject methodName]
的方法directlry不会[classObject methodName]
视图中的更改。 就像你想从scrollEnble = NO;
更改UIScrollView
属性scrollEnble = NO;
to scrollEnable = YES;
,它不会反驳。 你应该使用UIApplication
单例。
假设你要调用ViewController1'
S分析- (void)myMethod
在ViewController2
那么这里的步骤:
ViewController1
并创建其对象*vc
。 Delare属性@property @property (strong, nonatomic) ViewController1 *vc;
。 synthesize
也。 现在Viewcontroller1
类。 在你的Viewcontroller1
和viewDidLoad
导入AppDelegate.h
,如下所示:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.vc1 = self;
ViewController2.h
并导入AppDelegate.h
转到要调用ViewController2
方法的行,并按如下所示编写:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[appDelegate vc1] myMethod]; // to allow scrolling
理想情况下,您应该创建协议并委派方法来完成您要查找的内容。
创建协议,在secondViewController中实现它,并将协议委托设置为firstViewController,然后使用委托方法调用secondViewController中的相关方法
我希望这个对你有用..!!
一种方法是将声明更改为+(void) someMethod ;
在OneViewController.h中,并在实现文件中相应地将减号更改为加号。 这将使它成为类方法而不是实例方法。 然后在SecondViewController.m文件中,确保放入@class OneViewController;
在执行声明之前; 然后你可以调用[OneViewController someMethod]它应该执行。 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.