我在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中出现时调用 someMethod - secondViewController
(类似于[OneViewController someMethod]
),所以当我回到OneViewController时,我可以看到 someMethod 所做的更改。
我是否需要使用appDelegate方法?
我尝试过以下但不起作用。
neViewController *newViewController = [[OneViewController alloc] init];
[newViewController someMethod];
感谢您提前提供任何帮助..
答案 0 :(得分:4)
在SecondViewController中,声明OneViewController类的引用。您可以指定属性。在移动到SecondViewController之前设置引用。现在有了引用,您可以调用实例方法[_oneView someMethod]
。
修改强>
声明
OneViewController *_oneView;
同时添加assign属性
@property(nonatomic,assign) OneViewController *_oneView;
在.m文件中合成变量。
在显示OneViewController的SecondViewController时,只需添加以下行。
secondView._oneView = self;
答案 1 :(得分:3)
有时调用创建[classObject methodName]
的方法directlry不会反映视图中的更改。就像您想要将UIScrollView
属性从scrollEnble = NO;
更改为scrollEnable = YES;
一样,它也不会反复出现。
您应该使用UIApplication
的单身。
假设您要在ViewController1'
中调用- (void)myMethod
方法ViewController2
,请执行以下步骤:
ViewController1
并创建其对象*vc
。 Delare属性@property (strong, nonatomic) ViewController1 *vc;
。 synthesize
也是。现在来Viewcontroller1
课。在您AppDelegate.h
和Viewcontroller1
中导入viewDidLoad
,如下所示:
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
答案 2 :(得分:1)
理想情况下,您应该创建协议并委托方法来完成您要查找的内容。
创建协议,在secondViewController中实现它,并将协议委托设置为firstViewController,然后使用委托方法调用secondViewController中的相关方法
我希望它对你有用.. !!
答案 3 :(得分:-1)
这样做的一种方法是将声明更改为OneViewController.h中的+(void) someMethod ;
,并在实现文件中相应地将减号更改为加号。这将使它成为类方法而不是实例方法。然后在SecondViewController.m文件中,确保在实现声明之前放置@class OneViewController;
;然后你可以调用[OneViewController someMethod]它应该执行。干杯!