Common method in Swift


1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false

            }

            

        }

        return true

    }

2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){

 }else{

            return false

        }

      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result

    }

3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {

    

        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)

        }else{

            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)

            alert.show()

           

        }

    }

4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)

    {

        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)

        NSUserDefaults.standardUserDefaults().synchronize()

    }

    

    class func userDefaultForKey(key:String) -> String

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString

        

    }

    class func userDefaultForAny(key:String) -> AnyObject

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!

    }

    

    class func userdefaultForArray(key:String) -> Array<AnyObject>

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array

    }

    

    class func removeFromUserDefaultForKey(key:String)

    {

        NSUserDefaults.standardUserDefaults().removeObjectForKey(key)

        NSUserDefaults.standardUserDefaults().synchronize()

        

    }

5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height

Advertisements

Use HexColor in Swift as a color


Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)

   }

   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)

   }

}

Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

Creating Sliding Menu with iOS SlidingMenu Component


Introduction

This a component which is a menu has several buttons coming from the right and left side of the screen with an animation. Here is a small video that will give you the idea:

Click here for non HTML5 Video supported browsers

Integrating SlidingMenu

First you have to import SlidingMenu.h in your view controller “h” file.
You have to create an array which will hold buttons in your sliding menu. Like these:

#import “SlidingMenu.h”

@interface ViewController : UIViewController
{
    SlidingMenu *menu;
}
– (IBAction)openOrCloseMenu:(UIButton *)sender;
@property (strong, nonatomic) NSMutableArray *buttons;

@end

In your viewdidLoad method make these:

– (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @”Sliding Menu”;
    
    _buttons = [NSMutableArray array];
    [self createButtonsWithQuantity:7];
    menu = [[SlidingMenu alloc]init];
    [menu setButtonsArray:_buttons];

    
    // Do any additional setup after loading the view, typically from a nib.
}

This will create buttons that will  be in sliding menu. You can modify:

-(void)createButtonsWithQuantity:(NSInteger)quantity{
    for (int i = 0; i&lt;quantity; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button addTarget:self action:@selector(menuButonAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setBackgroundImage:[UIImage imageNamed:@&quot;button-blue&quot;] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@&quot;button-blue-pressed&quot;] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:[NSString stringWithFormat:@&quot;Button %i&quot;,button.tag] forState:UIControlStateNormal];
        button.layer.cornerRadius = 5.0;
        [self.view addSubview:button];
        [_buttons addObject:button];
    }
}

And the action method of the buttons of course:

– (void)menuButonAction:(UIButton *)sender {
    NSLog(@”%i. button clicked”,sender.tag);
    [self performSegueWithIdentifier:@”detail” sender:sender];
}

And decide when your sliding menu comes to the screen. I will do it in viewDidAppear method:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    for (UIButton *button in _buttons) {
        if (button != nil) {
            [self.view addSubview:button];
        }
    }
    [menu openOrCloseButtonsMenu];
}

If you use this in viewDidAppear method. Make sure you use this in viewDidDisappear method:

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [menu closeButtonsMenu];
    for (UIButton *button in _buttons) {
        [button removeFromSuperview];
    }
}

Customizing SlidingMenu

You can customize SlidingMenu with these properties:

Setting SlidingMenu Origins:

menu.buttonMenuOriginYOffset = 120;
menu.buttonMenuOriginXOffset = 10;

Setting Space between buttons:

menu.spaceBetweenButtons = 20;

Setting buttons size:

menu.buttonSize = CGSizeMake(73, 36);

Download Source Files from Git