31 Oct 2019

22 Nov 2018

To Run a method using Timer in background mode Swift..


If you want to run a code when app is in background state use below code :


   var bgTask = UIBackgroundTaskIdentifier()
        bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {

            UIApplication.shared.endBackgroundTask(bgTask)

        })
        let timer = Timer.scheduledTimer(timeInterval: 20, target: self, selector: #selector(notificationReceived), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)




@objc  func notificationReceived () {

        Print("Code here")

}

16 Mar 2018

How to give a Bottom line to a TextField iOS...

How to give a Bottom line to a TextField iOS...

To give a underline to textField (Only bottom border) line use the following code:



Here we use CALayer class to achieve it,

-(void)underlineToTextField:(UITextField *)txtField
{
CALayer *border = [CALayer layer];
CGFloat borderWidth = 0.8f;
    border.borderColor = [UIcolor greenColor].CGColor;
    border.frame = CGRectMake(0, text.frame.size.height -      borderWidth, ([[UIScreen mainScreen] bounds].size.width)-32, text.frame.size.height);
    border.borderWidth = borderWidth;
    [text.layer addSublayer:border];
    text.layer.masksToBounds = YES;
}

Call the method for which TextField you want to show underline like below,

[self underlineToTextField:textField];



How to make Shadow effect for View or Button.. etc on 4 sides iOS objective c...

How to make Shadow effect for View or Button.. etc on 4 sides iOS objective c...

1) 



2)
 
3)


Take UIView or Button... etc and make a Shadow effect as shown use the following code:

Set masks bounds to NO to display shadow visible 

  _viewBg.layer.masksToBounds = NO;

Set shadow Color

_viewBg.layer.shadowColor = [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.25f] CGColor];

Set Shadow radius

_viewBg.layer.shadowRadius = 5.0f// values depends on View Size

1) Use following to add Shadow top, left of View

_viewBg.layer.shadowOffset = CGSizeMake(-2.0f, -2.0f); // values depends on View Size

2) Use following to add Shadow bottom, right of View

_viewBg.layer.shadowOffset = CGSizeMake(2.0f, 2.0f); // values depends on View Size

3) Use following to add Shadow top, left, bottom, right of View

_viewBg.layer.shadowOffset = CGSizeZero;

4) Set Shadow opacity to full

_viewBg.layer.shadowOpacity = 1.0f;



11 Dec 2017

Expandable tableView Code Objective C...


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *expandTableView;

@end



#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *mainCategory;
    NSMutableArray *subCategory;
    NSMutableArray *expandStatusArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Intialize the main Category
    
    self.expandTableView.sectionFooterHeight = 0;
    
    mainCategory = [[NSMutableArray alloc] initWithObjects:@"MEN",@"WOMEN",@"KIDS",@"RECHARGE", nil];//@[@"",@"",@"",@""];
    
    
    subCategory = [[NSMutableArray alloc] initWithObjects:@[@"Cloths",@"Watches",@"Footwear"],@[@"Cloths",@"Jewellery",@"Footwear",@"Bangles"],@[@"Cloths",@"Toys"],@[@"Jio",@"Bsnl",@"Airtel",@"Uninor",@"Idea",@"vodafone"], nil];
    
    expandStatusArray = [[NSMutableArray alloc] initWithObjects:@"1",@"0",@"0",@"0",nil];
    //@YES for expand the cell
    //@NO for close the cell
    
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return mainCategory.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    NSString * status = [expandStatusArray objectAtIndex:section];

    if ([status isEqualToString:@"1"]) {
        NSArray *subArray = [subCategory objectAtIndex:section];
        return subArray.count;

    }
    return 0;
    
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
    }
    NSArray *subArray = [subCategory objectAtIndex:indexPath.section];
    NSString *dataStr = [subArray objectAtIndex:indexPath.row];
    cell.textLabel.text = dataStr;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    //Programatically create the view
    CGRect viewFrame = CGRectMake(0, 0, tableView.frame.size.width, 50);
    UIView *headerView = [[UIView alloc] initWithFrame:viewFrame];
    headerView.backgroundColor = [UIColor colorWithRed:76.0f/255.0f green:139.0f/255.0f blue:245.0f/255.0f alpha:1.0f];
    
    //Crate label programatically
    
    UILabel *headerLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    headerLbl.text = [mainCategory objectAtIndex:section];
    headerLbl.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:headerLbl];
    
    UIButton *expandBtn = [[UIButton alloc] initWithFrame:CGRectMake(tableView.frame.size.width-50, 0, 50, 50)];
    expandBtn.titleLabel.text = @"+";
    expandBtn.backgroundColor = [UIColor redColor];
    [headerView addSubview:expandBtn];
    expandBtn.tag = section;
    
    [expandBtn addTarget:self action:@selector(expandCell:) forControlEvents:UIControlEventTouchUpInside];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (void)expandCell:(UIButton*)button{
    
    NSString * status = [expandStatusArray objectAtIndex:button.tag];
    
    if ([status isEqualToString:@"1"]) {
        
        //Replace with o
        [expandStatusArray replaceObjectAtIndex:button.tag withObject:@"0"];
    }else{
        //Replace with 1
        [expandStatusArray replaceObjectAtIndex:button.tag withObject:@"1"];
    }
    [_expandTableView reloadData];

}










30 Nov 2017

How to Shuffle an Array in Swift...

If you want to shuffle an array use the following method pass an array get the Shuffled Array,


self.shuffledArray = self.ShuffleArray(answersArray: self.answersArray)


    func ShuffleArray(answersArray:[String]) -> [String] {
        var items = answersArray
        var shuffled = [String]();
        
        for _ in 0..<items.count
        {
            let rand = Int(arc4random_uniform(UInt32(items.count)))
            
            shuffled.append(items[rand])
            
            items.remove(at: rand)
        }
        
        return shuffled

    }


29 Nov 2017

How to add two NSDictionaries in Swift...

   The below code is an example of adding two dictionaries,
    
    var dict1 = ["One": "1","Two": "2","Three": "3","Four": "4"]
    let dict2 = ["Five": "5","Six": "6","Seven": "7","Eight": "8"]
    dict2.forEach { (k,v) in dict1[k] = v }
    print("Combined dictionary ===> ",dict1)
    
    And the Result is,
    

Result: Combined dictionary ===>  ["Two": "2", "Five": "5", "Three": "3", "Four": "4", "Six": "6", "One": "1", "Eight": "8", "Seven": "7"]

How to add two NSDictionaries into NSMutableDictionary Objective C...


The below code is an example of Adding Two Dictionaries into a Single mutableDictionary ,


  NSDictionary *dict1= [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"One",@"2",@"Two",@"3",@"Three",@"4",@"Four"nil];
    NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:@"5",@"Five",@"6",@"Six",@"7",@"Seven",@"8",@"Eight",nil];
    NSMutableDictionary *dictMerged  = [NSMutableDictionary dictionaryWithDictionary: dict1];
    [dictMerged addEntriesFromDictionary: dict2];
    
    NSLog(@"dictMerged===> %@",dictMerged);


/*
 Result: dictMerged===> {
Eight = 8;
Five = 5;
Four = 4;
One = 1;
Seven = 7;
Six = 6;
Three = 3;
Two = 2;
}
 */






27 Nov 2017

How to Create a Global UIAlertController in Swift...


 Add this code in any Class (As UIViewController extension)  as shown below

extension UIViewController {
    
    func alert(message: String, title: String ) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }
    

}


and call it anywhere(In  Any ViewController) as shown below,

   
self.alert(message: "Some message", title: "Title of Alert")

29 Sept 2017

How to set different colour Font text to single Label(Attributed Text)...



How to set different colour Font text to single Label(Attributed Text)...



-(NSAttributedString *)AttrStr:(NSString *)str1 fontString:(NSString *)str2 {
    
    NSDictionary *dict1;
    NSDictionary *dict2;
    
    dict1 = @{NSFontAttributeName:[UIFont fontWithName:promptLight size:10.0],NSForegroundColorAttributeName:[UIColor colorWithRed:127/255.0 green:127/255.0 blue:127/255.0 alpha:1.0]};
    dict2 = @{NSFontAttributeName:[UIFont fontWithName:promptLight size:10.0],NSForegroundColorAttributeName:[UIColor colorWithRed:78/255.0 green:186/255.0 blue:222/255.0 alpha:1.0]};
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
    [attString appendAttributedString:[[NSAttributedString alloc] initWithString:str1    attributes:dict1]];
    [attString appendAttributedString:[[NSAttributedString alloc] initWithString:str2   attributes:dict2]];
    
    return attString;

}




cell.LSALbl.attributedText =  [self AttrStr:@"LSA: " fontString:[NSString stringWithFormat:@"%ld",lroundf([_productionDataObj.lsaPlanned floatValue])]];

How to set background image to Navigation bar...



How to set background image to Navigation bar...


    UINavigationBar *navBar = self.navigationController.navigationBar;
    UIImage *img = [UIImage imageNamed:@"navImg.png"];
    [navBar setContentMode:UIViewContentModeScaleAspectFit];
    [navBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];

How to give different (Mixing of = Gradient colours)colours to View...



How to give different  (Mixing of = Gradient colours)colours to View...




@property (weak, nonatomic) IBOutlet UIView *navBgView;



  CAGradientLayer *gradientMask = [CAGradientLayer layer];
    gradientMask.frame = CGRectMake(0, 0, self.view.frame.size.width, 150);
    
    gradientMask.startPoint = CGPointMake(0.0, 0.5);   // start at left middle
    gradientMask.endPoint = CGPointMake(1.0, 0.5);     // end at right middle
    
    gradientMask.colors = @[(id)[UIColor colorWithRed:91/255.0 green:232/255.0 blue:200/255.0 alpha:0.7].CGColor,
                            (id)[UIColor colorWithRed:91/255.0 green:232/255.0 blue:200/255.0 alpha:0.7].CGColor,
                            (id)[UIColor colorWithRed:91/255.0 green:232/255.0 blue:200/255.0 alpha:0.5].CGColor,
                            (id)[UIColor colorWithRed:85/255.0 green:188/255.0 blue:222/255.0 alpha:0.5].CGColor,
                            (id)[UIColor colorWithRed:85/255.0 green:188/255.0 blue:222/255.0 alpha:0.7].CGColor,
                            (id)[UIColor colorWithRed:85/255.0 green:188/255.0 blue:222/255.0 alpha:0.7].CGColor];
    
    gradientMask.locations = @[@0.0, @0.10, @0.40, @0.80, @0.90, @1.0];
    [_navBgView.layer insertSublayer:gradientMask atIndex:0];

How to give a border to View or Cell like shown...


How to give a border to View or Cell like shown...



    cell.layer.cornerRadius = 8.0;
    cell.layer.shadowOffset = CGSizeMake(-1, -1);
    cell.layer.shadowRadius = 3.0;
    cell.layer.shadowOpacity = 0.2;
    cell.layer.masksToBounds = NO;
    [cell.layer setShadowColor: [UIColor blackColor].CGColor];

How to add Borderline to View...



How to add Borderline to View...


@property (weak, nonatomic) IBOutlet UIView *topView;



    // Add a bottomBorder.
    CALayer *bottomBorder = [CALayer layer];
    
    bottomBorder.frame = CGRectMake(0.0f, 39.0f, self.view.frame.size.width, 0.8f);
    bottomBorder.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.2].CGColor;
    [_topView.layer addSublayer:bottomBorder];

12 Aug 2017

How to make TabBar Transparent...



How to make TabBar Transparent...




    
    // Add this in App delegate...
    
    [[UITabBar appearance] setBarTintColor:[UIColor clearColor]];
    [[UITabBar appearance] setBackgroundImage:[UIImage new]];





How to Validate phone Number...



How to Validate phone Number...




 BOOL value=[self validatePhone:[NSString stringWithFormat:@"%@",PhoneNumberTF.text]];


#pragma  – mark PhoneNumber Validation Method
/**
 PhoneNumber validation

 @param phoneNumber => phoneNumber from phoneNumberTF text
 @return => Bool
 */
-(BOOL)validatePhone:(NSString *)phoneNumber
{
    NSString *phoneRegex = @"^((\\+)|(00))[0-9]{6,14}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [phoneTest evaluateWithObject:phoneNumber];

}

How to animate textField on the top of Keyboard while Editing...



How to animate textField on the top of Keyboard while Editing...



#pragma  – mark Textfield Delegate Methods..

-(void)textFieldDidBeginEditing:(UITextField *)textField  {
    
     [self animateTextField:textField up:YES withOffset:textField.frame.origin.y / 2];
}
-(void)textFieldDidEndEditing:(UITextField *)textField {
    
    [self animateTextField:textField up:NO withOffset:textField.frame.origin.y / 2];

}


#pragma  – mark Textfield Animation Method

-(void)animateTextField:(UITextField*)textField up:(BOOL)up withOffset:(CGFloat)offset
{
    const int movementDistance = -offset;
    const float movementDuration = 0.4f;
    int movement = (up ? movementDistance : -movementDistance);
    [UIView beginAnimations: @"animateTextField" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];

}

1 Jul 2017

Custom TableView cell registerNib Code...


Custom TableView cell registerNib Code...

#import "ViewController.h"
#import "TableViewCell.h" //Custom TableViewCell class

@interface ViewController ()
@end
static NSString* const cellIdentifier = @"TableViewCellid";
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.TableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.TableView.estimatedRowHeight = 44.0;
    self.TableView.rowHeight = UITableViewAutomaticDimension;
    
    self.TableView.delegate = self;
    self.TableView.dataSource = self;
    
    UINib *nib= [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [self.TableView registerNib:nib forCellReuseIdentifier:cellIdentifier];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 10;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TableViewCell *cell = [self.TableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    


}


Recent Posts

Codable demo

Link: https://www.dropbox.com/s/kw7c1kgv1628bh7/codableDemo.zip?dl=0