Dishant Rajput Dishant Rajput - 2 days ago 4
iOS Question

Make one method in view controller globally and call it to many view controllers

I want to make one single method and call it, to many view controllers. Help me? and i also want to alloc UIView or button or label on that Fixed View.

HERE IS MY CODE

.h

#import <UIKit/UIKit.h>

@interface UIOnlyView : UIView

+ (UIOnlyView *) sharedGlobalClass;

-(void)yourMethod;

@end


.m

+(UIOnlyView *)sharedGlobalClass {

static dispatch_once_t pred;
static id shared = nil;

dispatch_once(&pred, ^{
shared = [[super alloc] init];

});

return shared;
}

-(void)yourMethod{

NSLog(@"Method called");

UIView *customView=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

customView.backgroundColor=[UIColor redColor];

[self addSubview:customView];

}


But my Custom view is not show on my view controller class where i called this method.

Answer

Use a singleton like this

create a class for example GlobalClass with type NSObject

In .h class create this method

+ (GlobalClass *) sharedGlobalClass;
- (void) yourMethod : (UIView *) view;

Now in .m class

+ (GlobalClass *) sharedGlobalClass {

    static dispatch_once_t pred;
    static id shared = nil;

    dispatch_once(&pred, ^{
        shared = [[super alloc] init];

    });


    return shared;
}

- (void) yourMethod : (UIView *) view {
    UIView *customView=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

    customView.backgroundColor=[UIColor redColor];

    [view addSubview:customView];
}

Now you can call this method like this

[[GlobalClass sharedGlobalClass] yourMethod:self.view];

from any of your ViewController, you just have to import

#import "GlobalClass.h"
Comments