How to use Swift code in Objective C class


Screen Shot 2015-04-24 at 5.03.18 PM

Now you can easily use swift code in your objective C class.

Step 1. Go to packaging in Build setting and get Product Module Name. Change it or write any other name. see attached image.

Step 2. Go to Object c class in which you want to use Swift class. and import class as following.

#import “msy-Swift.h”

Where msy – Product Module Name

You don’t need to import all swift class .this line import all swift classes in your project in your class.

Step 3::

Assume your swift class method is


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()

           

        }

    }


You can call this func using your objective c code like following

[CommonClass commonAlert:@”Hi ” msg:@”How to use Swift code in Objective C class” curView:self];

Best Of Luck

Advertisements

Get Rs.10 cashback on recharges of Rs.50 & above.


PayTm on Android:: https://play.google.com/store/apps/details?id=net.one97.paytm&hl=en

Get Rs.10 cashback on recharges of Rs.50 & above. Use Code: APPCB50. Valid for 5 orders on Paytm App

Note:This code is applicable on Paytm Android,iOS & Windows Apps only

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

How to get UDID of your iOS device


There is two way to get UDID

  1. From iTune

2.From Xcode

1. From iTune You can get UDID using following step

  • Open itunes
  • You will get your device at right corner
  • Click on Summary tab and then double click on Identifier .then identifier will covert on UDID .

Screen Shot 2014-11-14 at 12.14.42 PM

Screen Shot 2014-11-14 at 12.15.04 PM

Screen Shot 2014-11-14 at 12.15.23 PM

  1. You can get UDID from Xcode using following steps

  • On Xcode menu, click on window and choose device.
  • select your device and your will your device’s UDID

Screen Shot 2014-11-14 at 12.44.38 PM

Screen Shot 2014-11-14 at 12.44.59 PM

Best of Luck

Lineage Technology , Lucknow India

http://www.lineagetechnology.com/

Use different font text in a Label in swift


let secondLabel=UILabel(frame: CGRectMake(0, 16, _screenWidth2, 20))

        secondLabel.textColor=UIColor.whiteColor()

        secondLabel.textAlignment=NSTextAlignment.Center

        secondLabel.font=UIFont(name: “Arial”, size: 12)

        bottomView.addSubview(secondLabel)

        

        let attrSting=NSMutableAttributedString(string: “I agree to the Terms of Service and Privacy Policy.”)

        

        NSLog(“text length is %d”, attrSting.length)

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(15, 16))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica”, size: 12), range: NSMakeRange(31,4 ))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(35, 15))

        

        secondLabel.attributedText=attrSting

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)

Custom UITableViewCell Using Interface Builder


Hey everyone, welcome to my first of many screencasts coming in the next few weeks. Today I am going to show you how to layout a UITableViewCell in Interface Builder and have a UITableView populate with those type of cells. I am adopting a new structure for my screencasts which will be 5 or so mintues of keynote slides giving background info followed by 20 – 25 mintues of step by step development. The entire video will be directly below this paragraph, but scrolling down you will see a text based step by step of the whole tutorial as well. Hope you guys enjoy.

Skill Level MEDIUM

Here is a link to the screencast to watch. We are working on getting an embedded version in, but I figure this is basically just as functional. Have fun!

Custom UITableViewCell Screencast Video

Source Code

Available Here

Background Information

picture-1

picture-2

picture-3

picture-4

picture-5

picture-6

picture-7

picture-8

picture-9

picture-10

picture-11

Building The App

Step 1

picture-12

This step shouldn’t require any extra information.

Step 2

picture-13

datasourceconnection

Step 3

picture-14

In CustomTableCellTutorialViewController.m you must define the two required UITableViewDataSource methods. These methods will fill up the table view with data. For now we will put in dummy data just to make sure all of our connections are working.

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return 10;

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @”Cell”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil){

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}

[cell setText:[NSString stringWithFormat:@”I am cell %d”, indexPath.row]];

return cell;

}

Step 4

picture-15

Here you will need to be in xCode and go to File -> New File…

Select Objective C Class and make sure it is a UITableViewCell subclass, depending on your version of the SDK selecting this will differ. Look around and you will find it, call it iCodeBlogCustomCell. With this done enter these IBOutlets in the iCodeBlogCustomCell.h file enter the following IBOutlets:

IBOutlet UILabel *articleName;
IBOutlet UILabel *authorName;
IBOutlet UILabel *date;

IBOutlet UIImageView *imageView;
IBOutlet UIView *viewForBackground;

Add the @property and synthesize them in the main.

Step 5

picture-16

This step does not require and code but does require a lot of work in Interface Builder. I highly recommend you watch the screencast to see the step by step procedure here. Essentially what I do is create a new View XIB file. Opening this, I delete the standard UIView in the XIB and drag a UITableViewCell from my library into my document window. I assign the UITableViewCell to be of type iCodeBlogCustomCell. With this done layout the interface with the proper elements and hook them up by right clicking on the UITableViewCell in the document window.

Step 6

picture-17

This is where the real magic is. We are going to return to CustomTableCellTutorialViewController.m and edit the UITableViewDataSource methods we implemented earlier. The code I use has me putting in 4 separate PNG files that I add to my project. You can find your own to put inside the cells. Make sure the UIImageView inside the cell is set for Aspect Fit so you don’t have to worry about resizing the images. The functions should be changed to be:

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 100;
}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @”iCodeBlogCustomCell”;

iCodeBlogCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil){
NSLog(@”New Cell Made”);

NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@”iCodeBlogCustomCell” owner:nil options:nil];

for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[iCodeBlogCustomCell class]])
{
cell = (iCodeBlogCustomCell *)currentObject;
break;
}
}
}

 

if(indexPath.row % 4 == 0)
{
[[cell authorName] setText:@”Collin Ruffenach”];
[[cell articleName] setText:@”Test Article 1″];
[[cell date] setText:@”May 5th, 2009″];
[[cell imageView] setImage:[UIImage imageNamed:@”1.png”]];
}

else if(indexPath.row % 4 == 1)
{
[[cell authorName] setText:@”Steve Jobs”];
[[cell articleName] setText:@”Why iPhone will rule the world”];
[[cell date] setText:@”May 5th, 2010″];
[[cell imageView] setImage:[UIImage imageNamed:@”2.png”]];
}

else if(indexPath.row % 4 == 2)
{
[[cell authorName] setText:@”The Woz”];
[[cell articleName] setText:@”Why I’m coming back to Apple”];
[[cell date] setText:@”May 5th, 2012″];
[[cell imageView] setImage:[UIImage imageNamed:@”3.png”]];
}

else if(indexPath.row % 4 == 3)

{
[[cell authorName] setText:@”Aaron Hillegass”];
[[cell articleName] setText:@”Cocoa: A Brief Introduction”];
[[cell date] setText:@”May 5th, 2004″];
[[cell imageView] setImage:[UIImage imageNamed:@”4.png”]];

}

return cell;
}