×

iOS Subclass Creation


How to create a subclass ?

Suppose , in one viewController you have to write 10's of thousands of lines which includes TableView , CollectionView , ScrollView etc. Now , we know that TableView has it's own delegates , CollectionView has it's own delegates and ScrollView has it's own delagates . So instead of writing each UIElement's delegate in one single viewController we can subclass each one.

So for TableView we create another class . For CollectionView we create another class. For ScrollView we create another class. And call those three methods from single ViewController. That makes code simplified.

Lets create one feedback form using subclass .

Final Output :-


Open Xocde, File > New > Project > Single View Application > Enter Project Name > Next.



Let's create one class also named "SubClassView"

Open Xcode, File > New > File > Cocoa Touch class > enter File name > Done



Write this code in SubClassView.h file

#import "SubClassView.h"
#import "UIView+Autolayout.h"

#define PADDING  12
@interface SubClassView()
{
    UIButton *buttonGood;
    UILabel *labelCompany;
    UIButton *buttonAverage;   
}
@end
@implementation SubClassView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        
        UIView *boxView = [[UIView alloc]init];
        [self addSubview:boxView];
        [boxView autolayout];
        [boxView leftAlign:PADDING];
        [boxView topAlign:PADDING];
        [boxView rightAlign:PADDING];
        [boxView height:44];
        boxView.backgroundColor = [UIColor whiteColor];
        boxView.layer.cornerRadius = 2.0;
    
     
        labelCompany = [[UILabel alloc]init];
        [self addSubview:labelCompany];
        [labelCompany autolayout];
        [labelCompany leftAlign:PADDING*2];
        [labelCompany centerYAlign];
        [labelCompany height:24];
        labelCompany.textColor = [UIColor blackColor];
        labelCompany.font = [UIFont fontWithName:@"Arial" size:16.0];
  
        
        buttonGood = [[UIButton alloc]init];
        [boxView addSubview:buttonGood];
        [buttonGood autolayout];
        [buttonGood rightAlign:PADDING];
        [buttonGood centerYAlign];
     
        [buttonGood setTitle:@"\uf10c Good" forState:UIControlStateNormal];
        [buttonGood setTitle:@"\uf05d Good" forState:UIControlStateSelected];
        [buttonGood setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [buttonGood setTitleColor:[UIColor greenColor] forState:UIControlStateSelected];
        [buttonGood addTarget:self action:@selector(buttonGoodSelected) forControlEvents:UIControlEventTouchUpInside];
        buttonGood.titleLabel.font = [UIFont fontWithName:@"FontAwesome" size:16.0];
        
        buttonAverage = [[UIButton alloc]init];
        [boxView addSubview:buttonAverage];
        [buttonAverage autolayout];
        [buttonAverage rightAlign:PADDING relativeToView:buttonGood];
        [buttonAverage centerYAlign];
        
        [buttonAverage setTitle:@"\uf10c Average" forState:UIControlStateNormal];
        [buttonAverage setTitle:@"\uf05d Average" forState:UIControlStateSelected];
        [buttonAverage setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [buttonAverage setTitleColor:[UIColor greenColor] forState:UIControlStateSelected];
        [buttonAverage addTarget:self action:@selector(buttonAverageSelected) forControlEvents:UIControlEventTouchUpInside];
        buttonAverage.titleLabel.font = [UIFont fontWithName:@"FontAwesome" size:16.0];        
    }
   return self;
}

-(void)setCompaniesDict:(NSMutableDictionary *)companiesDict
{
    _companiesDict = companiesDict;
    labelCompany.text = [companiesDict valueForKey:@"name"];
}

-(void)buttonAverageSelected
{
   NSMutableDictionary * feedbackDict = [[NSMutableDictionary alloc]init];
    if(buttonAverage.selected)
    {
        buttonAverage.selected = NO;
        [feedbackDict removeObjectForKey:[_companiesDict valueForKey:@"name"] ];
        [feedbackDict removeObjectForKey:@"feedbackTitle"];
        
    }
    else
    {
        buttonAverage.selected = YES;
        buttonGood.selected = NO;
        [feedbackDict setObject:[_companiesDict valueForKey:@"name"] forKey:@"title"];
        [feedbackDict setObject:@"AVERAGE" forKey:@"feedbackTitle"];      
    }
    [self.delegateRef feedbackArray:feedbackDict];
}

-(void)buttonGoodSelected
{
   NSMutableDictionary * feedbackDict = [[NSMutableDictionary alloc]init];
  if(buttonGood.selected)
  {
      buttonGood.selected = NO;
      [feedbackDict removeObjectForKey:[_companiesDict valueForKey:@"name"] ];
      [feedbackDict removeObjectForKey:@"feedbackTitle"];
  }
    else
    {
     buttonGood.selected = YES;
     buttonAverage.selected = NO;
     [feedbackDict setObject:[_companiesDict valueForKey:@"name"] forKey:@"title"];
     [feedbackDict setObject:@"GOOD" forKey:@"feedbackTitle"];
    }
  
    [self.delegateRef feedbackArray:feedbackDict];
}
@end

Write this code in Subclass.m file

#import <UIKit/UIKit.h>
@protocol FeedbackDelegate 
-(void)feedbackArray:(NSMutableDictionary *)feedbackDict;
@end
@interface SubClassView : UIView

@property(strong,nonatomic)NSMutableDictionary *companiesDict;
@property(weak,nonatomic)iddelegateRef;
@end

Write this code in ViewController.h file

#import "ViewController.h"
#import "SubClassView.h"

@interface ViewController ()  
{

    NSMutableArray *arrayCompanies;
    NSMutableArray *delegateFeedbackArray;
}
@end

@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    delegateFeedbackArray = [[NSMutableArray alloc]init];
    
    arrayCompanies = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0];
    NSMutableDictionary *codzifyDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Codzify",@"name", nil];
    [arrayCompanies addObject:codzifyDict];
    
    
    NSMutableDictionary *appleDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Apple",@"name", nil];
    [arrayCompanies addObject:appleDict];
    
    NSMutableDictionary *googleDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Google",@"name", nil];
    [arrayCompanies addObject:googleDict];
    
    NSMutableDictionary *microsoftDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Microsoft",@"name", nil];
    [arrayCompanies addObject:microsoftDict];
    
    NSMutableDictionary *amazonDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Amazon",@"name", nil];
    [arrayCompanies addObject:amazonDict];

  /* initialise Navigation Bar View */
     [self initialiseNavigationBarView];
   
  /* initialise Student Form View */
    [self initializeSubClassView];
}


-(void)initialiseNavigationBarView

{
  /* All about Navigation Controller Title , Back Button */
    NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    
  /* give Background color to navigation bar */
    if ([[ver objectAtIndex:0] intValue] >= 7) {
        // iOS 7.0 or later
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0/255.0 green:169/255.0  blue:98/255.0 alpha:1.0];;
        self.navigationController.navigationBar.translucent = NO;
    }else {
      // iOS 6.1 or earlier
        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0/255.0 green:169/255.0  blue:98/255.0 alpha:1.0];;
        self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0/255.0 green:169/255.0  blue:98/255.0 alpha:1.0];;
    }
    
  /* give title to navigation bar */
    self.navigationItem.title = @"Companies feedback";
    
    
    /* give Right Button to Navigation Bar */
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"save" style:UIBarButtonItemStylePlain target:self action:@selector(saveButtonClicked)];
    
  /* Chnage TextColor of Left Or Right BarButton on Navigation Item */
    [item setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItems = @[item];
    
  /* give titleColor to Navigation Title */
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:[UIColor whiteColor]}];

}

- (void)initializeSubClassView
{
    int y = 0;
    for(int i = 0; i < [arrayCompanies count] ; i++ )
    {
    SubClassView *viewSubClass = [[SubClassView alloc]initWithFrame:CGRectMake(0, y, self.view.frame.size.width, 60)];
    viewSubClass.delegateRef = self;
    viewSubClass.companiesDict =  [arrayCompanies objectAtIndex:i];
    [self.view addSubview:viewSubClass];
    y += 60;
    }
}

/* Subclass Feedback delegate */
-(void)feedbackArray:(NSMutableDictionary *)feedbackDict
{
    for(int i = 0; i<  [delegateFeedbackArray count] ; i++)
    {
        NSMutableDictionary *dict = [delegateFeedbackArray objectAtIndex:i];
        NSString *titleString = [dict valueForKey:@"title"];
        if([titleString isEqualToString:[feedbackDict valueForKey:@"title"]])
        {
            [delegateFeedbackArray removeObjectAtIndex:i];
          
        }
    }
    
    [delegateFeedbackArray addObject:feedbackDict];

}

#pragma mark - Actions
-(void)saveButtonClicked
{
    NSLog(@"Feedback Array Data %@",delegateFeedbackArray);
}