Thursday, 14 July 2016

Onclick Label calling with PhoneNumber in ios swift2

OnClick Label Calling with PhoneNumber

    1.  On click Label Call dynamically

      <***********Steps to create  calling Button**********>

      • Add code in info.plist

      </dict>
          <key>LSApplicationQueriesSchemes</key>
           <array>       
              <string>telprompt</string>
              <string>tel</string>
          </array>
      </dict>

      • Add label in ViewController dynamically by using CGPoints.
                //declare label

      let phoneNumberLabel:UILabel = UILabel(frame: CGRectMake(85, 220, 120, 45))

      //In viewDidLoad()
       override func viewDidLoad() {
              super.viewDidLoad()
       phoneNumberLabel.bounds = CGRectMake(CGRectGetMidX(self.view.frame), 220, 120, 45)
              phoneNumberLabel.text = "Click To Call"
              self.view.addSubview(phoneNumberLabel)
      }
      •  Create An touchesBegan Event in View Controller 

      override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
              for touch: AnyObject in touches {       
                  let location = touch.locationInView(self.view)
                  if CGRectContainsPoint(phoneNumberLabel.frame, location) {
                      UIApplication.sharedApplication().openURL(NSURL(string: "tel://1234567890")!)
                  }
              }
          }          

<*******OR********> 

<***********Steps to create  calling label with Outlet**********>

      1. Add pies of code in info.plist .

        </dict>
            <key>LSApplicationQueriesSchemes</key>
             <array>       
                <string>telprompt</string>
                <string>tel</string>
            </array>
        </dict>

      2. Add Label in Storyboard.
      3.   Create An Label Outlet in View Controller.

        @IBOutlet var callPhoneNumberLabel: UILabel!
      4. Create Function for Calling label.

        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
                for touch: AnyObject in touches {       
                    let location = touch.locationInView(self.view)
                    if CGRectContainsPoint(callPhoneNumberLabel.frame, location) {
                        UIApplication.sharedApplication().openURL(NSURL(string: "tel://1234567890")!)
                    }
                }
            }          

         

      5. Finished Run and Check ......happy Coding


Onclick Button calling with PhoneNumber in ios swift2

  1.  On click Button Call

    <***********Steps to create  calling Button**********>

    1. Add pies of code in info.plist

      </dict>
          <key>LSApplicationQueriesSchemes</key>
           <array>       
              <string>telprompt</string>
              <string>tel</string>
          </array>
      </dict>

    2. Add Button in Storyboard
    3.  Create An Button Action in View Controller 

      @IBAction func call(sender: AnyObject) {
      //Replace with your Phone Number
      UIApplication.sharedApplication().openURL(NSURL(string: "tel://1234567890")!)
      }

      <*******OR********>

      <***********Steps to create  calling Button with function**********>

    1. Add pies of code in info.plist 

      </dict>
          <key>LSApplicationQueriesSchemes</key>
           <array>       
              <string>telprompt</string>
              <string>tel</string>
          </array>
      </dict>

    2. Add Button in Storyboard
    3.  Create An Button Action in View Controller with callPhoneNumber Method.

      @IBAction func call(sender: AnyObject) { 
      //Replace with your Phone Number
      callPhoneNumber("1234567890")
      }
    4. Create Function with name callPhoneNumber() 

      private func callPhoneNumber(phoneNumber:String) {
              if let phoneCallURL:NSURL = NSURL(string: "tel://8050741946") {
                  let application:UIApplication = UIApplication.sharedApplication()
                  if (application.canOpenURL(phoneCallURL)) {
                      application.openURL(phoneCallURL);
                  }
              }
          }

       

    5. Finished Run and Check ......happy Coding


Friday, 24 June 2016

How to create CheckBox buttons in ios swift2 Tutorial

For CheckBox Buttons there is nothing that comes built in Xcode iOS Swift2.

CheckBoxes

      You can yourself implement Checkboxes easily. You can set an unchecked_checkbox for your button for StateNormal and a checked_checkbox for your StateSelected. Now on taps the button will change its image and alternate between checked and unchecked image.

Steps to start designing RadioButtons

  1. Create new project in Xcode,Start up Xcode and go to File\New\Project. Select iOS\Application\Single View Application, and click Next. 

  2.  Create a custom class.

    • CheckBox.swift

     import UIKit

    class CheckBox: UIButton {
      
        //images
        let checkedImage = UIImage(named: "checked_checkbox")
        let unCheckedImage = UIImage(named: "unchecked_checkbox")
      
        //bool propety
        @IBInspectable var isChecked:Bool = false{
            didSet{
                self.updateImage()
            }
        }

      
        override func awakeFromNib() {
           // self.addTarget(self, action:#selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            self.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
            self.updateImage()
        }
      
      
        func updateImage() {
            if isChecked == true{
                self.setImage(checkedImage, forState: .Normal)
            }else{
                self.setImage(unCheckedImage, forState: .Normal)
            }

        }

        func buttonClicked(sender:UIButton) {
            if(sender == self){
                isChecked = !isChecked
            }
        }

    }

     3.ADD two images with name

    • checked_checkbo.png

    • unchecked_checkbox.png

     4.In storyboard 

    1. Drag and drop 3 buttons.
    2. Select button1,got to identity inspector and select the custom class as CheckBox.
    3. Repeate,steps 2 for button2,button3.

     

    5.Finally,run the xcode and check the output,its worked for me,thanks for following tutorial

Thursday, 23 June 2016

How to create radio buttons in ios swift2 Tutorial

 For Radio Buttons there is nothing that comes built in Xcode iOS Swift2.

 Radio Buttons

    Radio buttons are a special type of control that always appear in groups; they are typically displayed as a list of options with selectable buttons alongside. Their behaviour is also somewhat unique; any button within the group can be selected, but selecting one button will deselect all other buttons in the group. Only a single button, within the same group, can be selected at one time.

Steps to start designing RadioButtons

  1. Create new project in Xcode,Start up Xcode and go to File\New\Project. Select iOS\Application\Single View Application, and click Next. 

  2.  Create a two  custom classes,

    • NMPLRadioButton.swift

    • NMPLRadioButtonsController

 NMPLRadioButton.swift

import Foundation
import UIKit
@IBDesignable

class NMPLRadioButton: UIButton {

    private var circleLayer = CAShapeLayer()
    private var fillCircleLayer = CAShapeLayer()
    override var selected: Bool {
        didSet {
            toggleButon()
        }
    }
    /**
        Color of the radio button circle. Default value is UIColor red.
    */
    @IBInspectable var circleColor: UIColor = UIColor.redColor() {
        didSet {
            circleLayer.strokeColor = circleColor.CGColor
            self.toggleButon()
        }
    }
    /**
        Radius of RadioButton circle.
    */
    @IBInspectable var circleRadius: CGFloat = 5.0
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }

    private func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = 0 + circleLayer.lineWidth
        circleFrame.origin.y = bounds.height/2 - circleFrame.height/2
        return circleFrame
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    private func initialize() {
        circleLayer.frame = bounds
        circleLayer.lineWidth = 2
        circleLayer.fillColor = UIColor.clearColor().CGColor
        circleLayer.strokeColor = circleColor.CGColor
        layer.addSublayer(circleLayer)
        fillCircleLayer.frame = bounds
        fillCircleLayer.lineWidth = 2
        fillCircleLayer.fillColor = UIColor.clearColor().CGColor
        fillCircleLayer.strokeColor = UIColor.clearColor().CGColor
        layer.addSublayer(fillCircleLayer)
        self.titleEdgeInsets = UIEdgeInsetsMake(0, (4*circleRadius + 4*circleLayer.lineWidth), 0, 0)
        self.toggleButon()
    }
    /**
        Toggles selected state of the button.
    */
    func toggleButon() {
        if self.selected {
            fillCircleLayer.fillColor = circleColor.CGColor
        } else {
            fillCircleLayer.fillColor = UIColor.clearColor().CGColor
        }
    }

    private func circlePath() -> UIBezierPath {
        return UIBezierPath(ovalInRect: circleFrame())
    }

    private func fillCirclePath() -> UIBezierPath {
        return UIBezierPath(ovalInRect: CGRectInset(circleFrame(), 2, 2))
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        circleLayer.frame = bounds
        circleLayer.path = circlePath().CGPath
        fillCircleLayer.frame = bounds
        fillCircleLayer.path = fillCirclePath().CGPath
        self.titleEdgeInsets = UIEdgeInsetsMake(0, (2*circleRadius + 4*circleLayer.lineWidth), 0, 0)
    }

    override func prepareForInterfaceBuilder() {
        initialize()
    }
}

 NMPLRadioButtonsController.swift

import Foundation
import UIKit

/// RadioButtonControllerDelegate. Delegate optionally implements didSelectButton that receives selected button.
@objc protocol NMPLRadioButtonControllerDelegate {
    /**
        This function is called when a button is selected. If 'shouldLetDeSelect' is true, and a button is deselected, this function
    is called with a nil.
   
    */
    optional func didSelectButton(aButton: UIButton?)
}

class NMPLRadioButtonsController : NSObject
{
    private var buttonsArray = [UIButton]()
    private weak var currentSelectedButton:UIButton? = nil
    weak var delegate : NMPLRadioButtonControllerDelegate? = nil
    /**
        Set whether a selected radio button can be deselected or not. Default value is false.
    */
    var shouldLetDeSelect = false

    /**
        Variadic parameter init that accepts UIButtons.

        - parameter buttons: Buttons that should behave as Radio Buttons
    */
    init(buttons: UIButton...) {
        super.init()
        for aButton in buttons {
            aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
        }
        self.buttonsArray = buttons
    }
    /**
        Add a UIButton to Controller

        - parameter button: Add the button to controller.
    */
    func addButton(aButton: UIButton) {
        buttonsArray.append(aButton)
        aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
    }
    /**
        Remove a UIButton from controller.

        - parameter button: Button to be removed from controller.
    */
    func removeButton(aButton: UIButton) {
        var iteration = 0
        var iteratingButton: UIButton? = nil
        for( ; iteration<buttonsArray.count; iteration++) {
            iteratingButton = buttonsArray[iteration]
            if(iteratingButton == aButton) {
                break
            } else {
                iteratingButton = nil
            }
        }
        if(iteratingButton != nil) {
            buttonsArray.removeAtIndex(iteration)
            iteratingButton!.removeTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
            if currentSelectedButton == iteratingButton {
                currentSelectedButton = nil
            }
        }
    }
    /**
        Set an array of UIButons to behave as controller.
       
        - parameter buttonArray: Array of buttons
    */
    func setButtonsArray(aButtonsArray: [UIButton]) {
        for aButton in aButtonsArray {
            aButton.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside)
        }
        buttonsArray = aButtonsArray
    }

    func pressed(sender: UIButton) {
        if(sender.selected) {
            if shouldLetDeSelect {
                sender.selected = false
                currentSelectedButton = nil
            }
        } else {
            for aButton in buttonsArray {
                aButton.selected = false
            }
            sender.selected = true
            currentSelectedButton = sender
        }
        delegate?.didSelectButton?(currentSelectedButton)
    }
    /**
        Get the currently selected button.
   
        - returns: Currenlty selected button.
    */
    func selectedButton() -> UIButton? {
        return currentSelectedButton
    }
}

3.In storyboard 

  1. Drag and drop 3 buttons, 
  2. Select button1,button2,button3 create outlets for them in ViewController.
  3. Select button1,got to identity inspector and select the custom class NMPLRadioButton 
  4. Below define an userdefined runtime attributes,click on + button below left,set keypath as circleColor,type as Color and value as color  u want
  5. Next,click on + button below left,set keypath as circleRadius,type as Number and value as ex..,10,20  u want.
  6. Repeate,steps 3,4,5 for button2,button3.

4.Copy the Code Snippet in ViewController.swift.

ViewController.swift

import UIKit

class ViewController: UIViewController, NMPLRadioButtonControllerDelegate {

    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var button3: UIButton!

    var radioButtonController: NMPLRadioButtonsController?
   
    override func viewDidLoad() {
        super.viewDidLoad()
       
        radioButtonController = NMPLRadioButtonsController(buttons: button1, button2, button3)
        radioButtonController!.delegate = self
        radioButtonController!.shouldLetDeSelect = true

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

    func didSelectButton(aButton: UIButton?) {
        print(aButton)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

5.Finally,run the xcode and check the output,its worked for me,thanks for following tutorial.


Thursday, 24 September 2015

Add Image to layout on touch in android

Add image to drawable then add java part and xml below shown

///////////MainActivity.java////////////

package com.example.lucky10021992.ontouchpointlocation;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RelativeLayout rr = (RelativeLayout) findViewById(R.id.rr);
        rr.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);
                    ImageView iv = new ImageView(getApplicationContext());
                    lp.setMargins(x, y, 0, 0);
                    iv.setLayoutParams(lp);
                    iv.setImageDrawable(getResources().getDrawable(
                            R.drawable.ic_launcher));
                    ((ViewGroup) v).addView(iv);
                }
                return false;
            }
        });
}


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

//////////////activity_main.xml///////////////

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rr"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

</RelativeLayout>

I hope it works,thank u;,

Get the co-ordinates of a touch event on Android

/////////////////////////////MainActivity Java Code:////////////////////////////

package com.example.lucky10021992.Ontouchpointlocation;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textView = (TextView)findViewById(R.id.textView);
        // this is the view on which you will listen for touch events
        final View touchView = findViewById(R.id.touchView);
        touchView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                textView.setText("Touch coordinates : " +
                        String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
                return true;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


///////////////////////////// XML Code:////////////////////////////

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:id="@+id/touchView"
        android:background="#f00"
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, TestActivity"
        />
</LinearLayout>

I Hope it works thank u;,


Wednesday, 9 September 2015

Error:Execution failed for task ':app:processDebugResources'. > com.android.ide.common.internal.LoggedErrorException: Failed to run command: C:\Users\lucky10021992\AppData\Local\Android\sdk\build-tools\22.0.1\aapt.exe package -f --no-crunch -I C:\Users\lucky10021992\AppData\Local\Android\sdk\platforms\android-22\android.jar -M C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\manifests\full\debug\AndroidManifest.xml -S C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\res\debug -A C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\assets\debug -m -J C:\Users\lucky10021992\Desktop\Split\app\build\generated\source\r\debug -F C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\res\resources-debug.ap_ --debug-mode --custom-package com.example.lucky10021992.split -0 apk --output-text-symbols C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\symbols\debug Error Code: 1 Output: C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\res\debug\values-v23\values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'. C:\Users\lucky10021992\Desktop\Split\app\build\intermediates\res\debug\values-v23\values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.

Compare the two build.gradle (Module:app) 

Newly created Project Build.Gradle(Module:app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.newProject"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.3'
}
Previous Project Build.Gradle(Module:app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.example.previousProject"
        minSdkVersion 11
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}
  • Replace all redSelected with previous project Build.Gradle
  • Sync project and build project
It works for me try it.