简体   繁体   中英

call method in UIButton Action in another class

I have one class UIViewController and Inside I have one button , I want to call one method from another class would you please help me to implement the action for my button

I'm new to objective-c

my button Action in UIViewController :

- (IBAction)ActionButton:(id)sender {
NSLog(@"A1");


}

my method in WebViewControlle r:

    -(void)loadWebView{

    NSURL *url = [NSURL fileURLWithPath:[ [ NSBundle mainBundle ] pathForResource:  
    @"TestName/TestName1/Test1Name1" ofType:@"html" ]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

   }

my question is how to call this method to my button since it's in another view? I have one method in my WebViewController and I want to call it from one button that I have in UIViewController

You could try this:

Say you have a class called ViewA which implements the method.

If you want the button action to invoke that method, you need to have an instance of another class.

-(void)loadWebView{

NSURL *url = [NSURL fileURLWithPath:[ [ NSBundle mainBundle ] pathForResource:  
@"TestName/TestName1/Test1Name1" ofType:@"html" ]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

}

For you button VIEW:

#import "ViewA.h"

ViewA *instanceOfViewA;
// assign an instance to instanceOfViewA

Your Button method:

- (IBAction)ActionButton:(id)sender {
NSLog(@"A1");
    [yourButton addTarget:instanceOfViewA
                  action:@selector(loadWebView)
        forControlEvents:UIControlEventTouchUpInside];

}

You may store a reference to WebViewController in your main view controller and send a message to that reference, check my answer .

code:

in MyViewController.h :

@class WebViewController;
...
@interface MyViewController
{
    ...
}
@property (nonatomic, retain) IBOutlet WebViewController* webViewController;
...

in MyViewController.m :

#import "WebViewController.h"
...
@implementation MyViewConroller
@synthesize webViewController;

...
- (void) dealloc {
    ...
    self.webViewController = nil;
    ...
    [super dealloc];
}

Assign your WebViewController (like you did with buttons and stuff) in IB and then in code:

- (IBAction)ActionButton:(id)sender {
    NSLog(@"A1");
    [self.webViewController loadWebView];
}

您可以在UIViewController中使用通知或委托或具有WebViewController的引用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM