Saturday 6 December 2014

Jogendra Singh

UITableview with UISearchBar in swift Language

Create UISearchBar with UITableView in swift language ( iOS8 ). 


In this tutorials we are going to learn how to work UISearchBar with UITableView in swift language .
        UISearchBar Class implements a simple a text field for searches . UISearchBar object does not perform direct we need to user UISearchBarDelegate for this and implement the action when text entered and button clicked.



First Need to create UITableView in swift  : -  How to create / make a simple tableview in iOS8 and swift

Now need to implement UISearchBar in this

   Create global objects  : -

    @IBOutlet var tableView:UITableView!   // This is for your tableview
    
    @IBOutlet var searchBarObj:UISearchBar!  // It's for your search bar object 
    
    var is_searching:Bool!   // It's flag for searching  
    var dataArray:NSMutableArray!  // Its data array for UITableview 
    var searchingDataArray:NSMutableArray! // Its data searching array that need for search result show 


Add Delegate of UITableView and UISearchbar

class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate


Now initialise all array and search flag

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        is_searching = false
        dataArray = ["Apple", "Samsung", "iPHone", "iPad", "Macbook", "iMac" , "Mac Mini"]
        searchingDataArray = []
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
    }

Now we need to minor change in UITableViewDataSource functions


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if is_searching == true{
            return searchingDataArray.count
        }else{
            return dataArray.count  //Currently Giving default Value
        }
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        if is_searching == true{
            cell.textLabel.text = searchingDataArray[indexPath.row] as NSString
        }else{
            cell.textLabel.text = dataArray[indexPath.row] as NSString
        }
        return cell;
    }

Hows show in simulator now : -





Now need to implement UISearchBar Delegate function


    func searchBar(searchBar: UISearchBar, textDidChange searchText: String){
        if searchBar.text.isEmpty{
            is_searching = false
            tableView.reloadData()
        } else {
            println(" search text %@ ",searchBar.text as NSString)
            is_searching = true
            searchingDataArray.removeAllObjects()
            for var index = 0; index < dataArray.count; index++
            {
                var currentString = dataArray.objectAtIndex(index) as String
                if currentString.lowercaseString.rangeOfString(searchText.lowercaseString)  != nil {
                    searchingDataArray.addObject(currentString)
                    
                }
            }
            tableView.reloadData()
        }
      } 

After searching we can result showing according to our search 





Using this delegate function we can search text using UISearchBar   in UITableView

Download Sample Project from here : - UITableView with SearchBar xCode Project


Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 
Read More

Monday 24 November 2014

Jogendra Singh

UISwitch example in swift ios8


How to make UISwitch button in swift language ?


   UISwitch button is return a boolean value like : - true , false , yes , no etc.  In this tutorial we're going to learn example of UISwitch button in swift language, 


Open Object and create new project for UISwitch button .  name of project is "UISwitchExampleSwift" and select language is SWIFT.




Now go in Main.storyboard and drag and drop UISwitch button and One UILabel for showing current state of UISwitch button . 



Now Make object of both UISwitch button and UILabel or also make action of UISwitch Like this :- 

    @IBOutlet
           var switchBtnObj : UISwitch!

    @IBOutlet
 var stateLabelObj : UILabel

and Action of UISwitch button :-

 @IBAction func switchBtnClicked   (switchBtn : UISwitch ){
            } 


Connect both of in Storyboard like this :-



Now need to check in Action using if condition like this :- 

    @IBAction func switchBtnClicked   (switchBtn : UISwitch ){
        if switchBtn.on{
            stateLabelObj.text = "Switch btn is on now"
        }else{
            stateLabelObj.text = "Switch btn is off now"
        }
    }

And change in display :-   If button is off 


Check if Button is On




Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 







Read More

Saturday 22 November 2014

Jogendra Singh

Image Resize in swift ios8

How  to resize an image?

In this tutorials We are going to learn "How can resize UIImage in swift language".  Without resize image we can get full image in our view  

First I am showing image that in original size 



If we check this image size than we see image size is "1366 × 768" .
We're not able to show full image in our iPhone screen.

Now Need to check How looks this iPhone without resize 

Setting image in backgroud of UIView


        self.view.backgroundColor = UIColor(patternImage:UIImage(named: "bg Image.jpg")!)

After doing this setup, we see in simulator this type .


In this image we can see image's only few part is showing., so we need to resize image 


Resizing UIImage in swift 

I have made function that can we use for resize image, In that we need to pass original image and size that we need . 

    func imageResize (imageObj:UIImage, sizeChange:CGSize)-> UIImage{
        
         let hasAlpha = false
        let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
        
        UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale)
        imageObj.drawInRect(CGRect(origin: CGPointZero, size: sizeChange))
        
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        return scaledImage
    }


How to call this function  : - 


               var mainScreenSize : CGSize = UIScreen.mainScreen().bounds.size // Getting main screen size of iPhone
        
             var imageObbj:UIImage! =   self.imageResize(UIImage(named: "bg Image.jpg")!, sizeChange: CGSizeMake(mainScreenSize.width, mainScreenSize.height))
        
   self.view.backgroundColor = UIColor(patternImage:imageObbj) 



After doing this setup we see again image in device that looks like this :-





   We can see in this image is fit in screen .





Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 



Read More

Friday 21 November 2014

Jogendra Singh

UIPickerView make in Swift iOS


How to make or create UIPickerView in swift language


What is pickerview : - UIPickerView use for user select value by rotating the wheel for his desired value.  In pickerview have rows and component for user interface .  


Going to learn UIPickerView : -  

                  Open xCode and create new project UIPickerViewSwift  and select Swift language .


Now go in ViewController.swift and create Object of picker view 

    @IBOutlet
    var pickerViewObj : UIPickerView!

  Now go in storyboard and drag and drop UIPickerView and connect to object like this :- 






also connect delegate and datasource  

adding datasource and delegate in ViewController.swift

class ViewController: UIViewController ,UIPickerViewDataSource, UIPickerViewDelegate  {
          }



Create content array that you want to show on PickerView

    var pickerValueArray = ["Welcome", "on", "our", "site", "jogendra.com"]

Add datasource and delegate function of pickerview

  func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
    {
        return 1;
    }
    
    // returns the # of rows in each component..
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
    {
        return pickerValueArray.count;
    }

//Title showing
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
    {
        return pickerValueArray[row]
    }

  For Selection value add this 
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        NSLog("Value Printing %@",pickerValueArray[row]);
        
     }






Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 






Read More

Monday 17 November 2014

Jogendra Singh

How to make UIDatePicker in iOS with Swift


Here we are going to learn UIDatePicker in swift :-


       The Date Picker in iOS 8 provides an custom Picker View that uses multiple rotating wheels to allow users to select dates and times. In this tutorial the current selected date is presented onscreen inside a label. This tutorial is written in Swift so you will need Xcode 6. It can be downloaded at Apple's developer portal.



        Open Xcode and create a new Single View Application. For product name, use UIDatePickerSwift  and then fill out the Organization Name (ex. jogendra) and Organization Identifier (Ex. com.jogendra.datePicker) with your customary values. Enter Swift as Language and make sure only iPhone/iPad/Universal is selected in Devices.



      Drag a UILabel or  UITextField (According to your requirement ) to the View Controller change the UILabel or  UITextField text to "Select Date". Next, drag a Date Picker to the View Controller and center it. The Storyboard should look like this.



Create object of both UIDatePickerView and UITextField :- 

class ViewController: UIViewController {

    @IBOutlet
    var textField:UITextField!
    
    @IBOutlet
    var datePickerObj:UIDatePicker
        }


And Make action of UIDatePickerView
      @IBAction  func datePickerClicked( datePicker:UIDatePicker){
                 }

Connect in Storyboard




After doing these steps  do work in function of datepicker for change value 

    @IBAction  func datePickerClicked( datePicker:UIDatePicker){
        
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
        var dateStr = dateFormatter.stringFromDate(datePicker.date)
        textField.text = dateStr
        
    }

It's look like this :-
Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+ 









Read More

Tuesday 11 November 2014

Jogendra Singh

In iOS UIWebView create / make in Swift / iOS Sdk



How to create UIWebview programmatically create in swift and iOS 8 .


In this tutorial going to learn about UIWebview :-   

Some times we need to open some url or load some html content in our application

Creating UIWebview 
override func viewDidLoad() {
    super.viewDidLoad()
    let webV:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    webV.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.jogendra.com")))
    webV.delegate = self;
    self.view.addSubview(webV)
}

How to use UIWebview delegate in swift language

First need to you take delegate in your header file

class myViewController: UIViewController, UIWebViewDelegate 

Now need to add delegate functions on UIWebview .. 


func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) {
    print("Webview fail with error \(error)");
}

func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -&gt; Bool {
    return true;
}

func webViewDidStartLoad(webView: UIWebView!) {
    print("Webview started Loading")
}

func webViewDidFinishLoad(webView: UIWebView!) {
    print("Webview did finish load")
}


Thanks for Visit  , Also can visit on My blog Facebook page iPhone & iPad Application Development Help World and also can visit Google+
Read More

Friday 17 October 2014

Jogendra Singh

SWIFT - Show Current Location and Update Location in a MKMapView

Current Location and Update Location in a MKMapView in swift


Question :  I want to do a simple view with a map (MKMapView). I want to find and update the location of the user (like in the Apple Map app).



You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}
NOTE: If your target is iOS 8, you must include the NSLocationAlwaysUsageDescription key in your Info.plist to get the location services to work.
Read More
Jogendra Singh

How create button programmatically in Swift?

UIButton programmatically with the targetAction

How create button programmatically in Swift?


override func viewDidLoad() {
    
    super.viewDidLoad()
    
    let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.frame = CGRectMake(100, 100, 120, 50)
    button.backgroundColor = UIColor.greenColor()
    button.setTitle("Test Button", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    
    self.view.addSubview(button)
}

func buttonAction(sender:UIButton!)
{
    println("Button tapped")
}
Read More

Saturday 13 September 2014

Jogendra Singh

How create UILabel programmatically in Swift?

       How create UILabel programmatically in Swift? 


       How can I create UILabel programmatically using Swift language in Xcode 6? I create a new project in Xcode 6 and select Swift language for this project.

        var label = UILabel(frame: CGRectMake(5, 100, 200, 50 ))
        
        label.textAlignment = NSTextAlignment.Center
        
        label.backgroundColor = UIColor.redColor()
        
        label.text = "hello";
        
        label.tag = 5;

        
        self.view.addSubview(label);

  •        Access label value using tag value of label. 

          
            var theLabel : UILabel  = self.view.viewWithTag(5) as UILabel 
          
            // here accessing label using tag value 
  theLabel.text = "working fine"


 Thanks for visit here, leave you feedback here 
Read More
Jogendra Singh

How do you create a UIImageView programmatically in swift


UIImageView class provides a view container for displaying either a single image or for animating a series of images. In this example we are going to display an image inside a frame that is smaller in size. With the help of ContentMode UIViewContentModeScaleAspectFit we can scale the content to fit the size of the view by maintaining the aspect ratio. Please see the reference Guide for other content modes that may help you set the image respective to the view frame. In this tutorial we are going to learn the following
  • Display an image on the screen
  • How to resize the image to fit the view frame
  • Animate a series of images

var imageViewObject :UIImageView
imageViewObject = UIImageView(frame:CGRectMake(0, 0, 100, 100));
imageViewObject.image = UIImage(named:"imageName.png")
self.view.addSubview(imageViewObject)

  • How to resize the image to fit the view frame
imageViewObject.contentMode = UIViewContentMode.ScaleToFill
  or
imageViewObject.contentMode = UIViewContentMode.ScaleAspectFit
or
imageViewObject.contentMode = UIViewContentMode.ScaleAspectFill

  • Animate a series of images
        UIView.animateWithDuration(1.0,
                         delay: 2.0,
                         options: .CurveEaseInOut | .AllowUserInteraction,
                 animations: {
                      self. imageViewObject.center = CGPoint(x: 75, y: 200)
                },
                 completion: { finished in
                       println("Bug moved left!")
        }) 

Read More

Monday 4 August 2014

Jogendra Singh

Route path drawing using Google Map with iOS Sdk

Getting the Google Maps SDK for iOS

Before starting I want to tell, I have already done a example for this you can find this here...

Example Download Form Here


Click Here : - Google-Route-Path-Draw-Using Google Map




The Google Maps SDK for iOS is distributed as a zip file containing a static framework. After downloading the SDK, you will need to obtain an API key before you can add a map to your application.
Complete release notes are available for each release.










The Google Maps API Key

Using an API key enables you to monitor your application's Maps API usage, and ensures that Google can contact you about your application if necessary. The key is free, you can use it with any of your applications that call the Maps API, and it supports an unlimited number of users. You obtain a Maps API key from the Google APIs Console by providing your application's bundle identifier. Once you have the key, you add it to your AppDelegate as described in the next section.










The Google Maps URL scheme is available without an API key.

Obtaining an API Key

You can obtain a key for your app in the Google APIs Console.
  1. Create an API project in the Google APIs Console.
  2. Select the Services pane in your API project, and enable the Google Maps SDK for iOS. This displays the Google Maps Terms of Service.
  3. Select the API Access pane in the console, and click Create new iOS key.
  4. Enter one or more bundle identifiers as listed in your application's .plist file, such as com.example.myapp.
  5. Click Create.
  6. In the API Access page, locate the section Key for iOS apps (with bundle identifiers) and note or copy the 40-character API key.
You should repeat this process for each new application.

Adding the Google Maps SDK for iOS to your project

The Google Maps SDK for iOS is packaged as a static framework with an included resource bundle. Before you can add a map to your application, you will need to add the framework to your project, and configure your build settings in Xcode. These instructions assume an installation for a new project. If you are working with an existing project, you may not have to follow the steps exactly as described.
  1. Launch Xcode and either open an existing project, or create a new project.
    • If you're new to iOS, create a Single View Application, and disable Use Storyboards but ensure that Use Automatic Reference Counting is on.
  2. Drag the GoogleMaps.framework bundle to the Frameworks group of your project. When prompted, select Copy items into destination group's folder.
  3. Right-click GoogleMaps.framework in your project, and select Show In Finder.
  4. Drag the GoogleMaps.bundle from the Resources folder to your project. We suggest putting it in the Frameworks group. When prompted, ensure Copy items into destination group's folder is not selected.
  5. Select your project from the Project Navigator, and choose your application's target.
  6. Open the Build Phases tab, and within Link Binary with Libraries, add the following frameworks:
    • AVFoundation.framework
    • CoreData.framework
    • CoreLocation.framework
    • CoreText.framework
    • GLKit.framework
    • ImageIO.framework
    • libc++.dylib
    • libicucore.dylib
    • libz.dylib
    • OpenGLES.framework
    • QuartzCore.framework
    • SystemConfiguration.framework
  7. Choose your project, rather than a specific target, and open the Build Settings tab.
    • In the Other Linker Flags section, add -ObjC. If these settings are not visible, change the filter in the Build Settings bar fromBasic to All.
  8. Finally, add your API key to your AppDelegate.
    • #import <GoogleMaps/GoogleMaps.h>
    • Add the following to your application:didFinishLaunchingWithOptions: method, replacing API_KEY with your API key.
      [GMSServices provideAPIKey:@"API_KEY"];









  • Upgrade from an earlier version

    To upgrade an existing project to the most recent version of the SDK, do the following:
    1. In the Project Navigator, replace the previous framework with the most recent framework.
    2. (Optional) Make any necessary changes as a result of the upgrade. Necessary changes will be described in the release notes.
    3. Clean and rebuild your project by selecting: Product > Clean and then Product > Build.

    Add a Map

    After adding the SDK to your project, and adding your key, you can try adding a map to your application. The code below demonstrates how to add a simple map to an existing ViewController. If you're creating a new app to iOS, first follow the installation instructions above, and create a new Single View Application; disabling Use Storyboards but enabling Use Automatic Reference Counting (ARC).
    Now, add or update a few methods inside your app's default ViewController to create and initialize an instance of GMSMapView.
    #import "YourViewController.h"
    #import <GoogleMaps/GoogleMaps.h>
    @implementation YourViewController {
      GMSMapView *mapView_;
    }
    - (void)viewDidLoad {
      // Create a GMSCameraPosition that tells the map to display the
      // coordinate -33.86,151.20 at zoom level 6.
      GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                              longitude:151.20
                                                                   zoom:6];
      mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
      mapView_.myLocationEnabled = YES;
      self.view = mapView_;
    
      // Creates a marker in the center of the map.
      GMSMarker *marker = [[GMSMarker alloc] init];
      marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
      marker.title = @"Sydney";
      marker.snippet = @"Australia";
      marker.map = mapView_;
    }
    @end
    
    Note: Replace both instances of YourViewController in the above example with the name of your View Controller.
    Run your application. You should see a map with a single marker centered over Sydney, Australia. If you see the marker, but the map is not visible, confirm that you have provided your API key.
  • Read More