Tuesday, 14 July 2015

Delete a row in table view IOS

Delete a Row from Table View in IOS



Learn Objective C from here:Click Here

Learn Swift from Here:Click Here

Learn Initializers in Objective C:Click Here


Learn Inheritance in Swift:Click here

Learn IOS Application Development From here:Click Here

Learn Attractive Table View in IOS:Click Here.

Learn Accessory Type in IOS:Click Here

As you have seen in my last tutorials of OtherButton Title manages in  Alert View,Not Read:Click Here.

Deleting a row from table view is very easy just use of one method. In General Table View is represented in Normal Mode.
There is one method behind commitEditingStyle for table view which put table view in Editing mode.

It placed Delete button on right Side automatically.
General Delegate of table view search for EditingStyle method. If it find then when you swipe your row of table view to left it shows you delete button.

Add following code:

-(void)TableView:(UITableView *)TableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
}
It looks like below:



You can also delete a row from table view by long Pressing On row of table view but you need to add Gestures. But you are not familiar about gestures currently.
I will describe a tutorials about gestures deletion row lator on.


Now delete a row from array with removeObject,removeObjectAtIndex any method.


-(void)TableView:(UITableView *)TableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[studentdata removeObjectAtIndex:indexPath.row];
}

Now row is removed we need to call again Data because it assigned before application is start or during load view in viewdidload method. So table view need to load again.

just write [tableview reloaddata];

below removeObjectAtIndexPath method.

Now the row is deleted from TableView.

It look like:



What happens when you build code again the row comes again. It is due to Loading of Method before the view is loaded the data is loaded into array again. 


Above method of deletion is used on that cases where default values are taken and asked user to remove it according to your need. 

Above method of delete row from table view temporary.


Ok i will give you the solution of it so that Next time you start or build application it will manages array from new data not previous.

Add this code in commitEditingStyle method.
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    lastElements=[studentdata objectAtIndex:indexPath.row];
    k=[studentdata indexOfObject:lastElements];
    NSUserDefaults *alltime=[NSUserDefaults standardUserDefaults];
    [alltime setInteger:k forKey:@"lastvalue"];
    [alltime synchronize];
    [studentdata removeObjectAtIndex:indexPath.row];
    [tableView reloadData];
}
Now add Below code in loadStudentData:
-(void)loadStudentData
{
    
    NSUserDefaults *alltime=[NSUserDefaults standardUserDefaults];
    l=[alltime integerForKey:@"lastvalue"];
    studentdata =[NSMutableArray arrayWithObjects:@"def",@"hjk",@"jko",
                  nil];
 int i;
        for (i=0; i<[studentdata count]; i++) {
            if ([studentdata objectAtIndex:l]==[studentdata objectAtIndex:i]) {
                [studentdata removeObjectAtIndex:l];
            }
        }
}

Now add in Interface the variables we used:
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

{
    NSMutableArray *studentdata;
     NSString *lastElements;
    NSInteger k;
    NSInteger l;
}

I have use Session but you are not familiar with NSUserDefault Currently. I will Describe it lator.
I have used it save Index of value which delete last time before the next time application start.

Then you would say when i build third time the application why the First row comes again.
The solution to it is i have used a single variable to store previous value you can add array so the value next will not passed.


Source Code Available here:Download here.

I hope you like my tutorials.Any query can mail me or comment here.





My next tutorials will be more options when Swipe the cell.


Monday, 13 July 2015

Other Button Title in Alert View IOS

OtherButtonTitle in UIAlertView IOS


Learn Objective C from here:Click Here

Learn Swift from Here:Click Here

Learn Initializers in Objective C:Click Here


Learn Inheritance in Swift:Click here

Learn IOS Application Development From here:Click Here

Learn Attractive Table View in IOS:Click Here.

Learn Accessory Type in IOS:Click Here

As you have studied my last tutorial of Attractive Table View in IOS if you have not read that tutorial: Click Here

Due to High Demand of One Visitor on my blog Today i am Published a post on Delegate in AlertView.







Let we start with UIAlertView.You have seen in last tutorials very heavily i used UIAlertView.
It is the Popup View appear above the main container or view of user interface.In UIAlert View Method you have seen code like below:

 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:@"ABC is Student" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];

you see in above code we have take delegate nil due to nil use of otherButtonTitles.In CancelButtonTitle i have write OK when user click on it,Popup View is automatically dismiss due to method written for cancelButtonTitle already.OtherButtonTitle is make for user defined button linked with code.Also if user want to run their code with other button he can bind it.

What is delegate?

Delegate is Object responsible for behaviour of UIAlertView.

There are two ways to addOtherButtonTitles.
One way to add Other Button Title is:

 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:@"ABC is Student" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Store", nil];
    [alert show];




Why i take delegate as Self?

Self means call with same object from which alert view is called.
I already describe the tutorials on Self and Super can see from here:Click Here.

Second way to write OtherButtonTitle is:

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:@"ABC is Student" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert addButtonWithTitles:@"Store"];
    [alert show];

Now you have seen i have added Store button on AlertView.But what happen when you click on it there is no code to executed it dismiss the popup view. you can also bind your code with Store Button.

There is method in Protocol UIAlertViewDelegate.If you have not studied about protocol you can: Click Here.

Add <UIAlertViewDelegate> at top of Interface in ViewController.h file.

 didDismissWithButtonIndex method is used which describe what code to execute when dismisspopupview with button index.
There is array of Indexes of button on AlertView. You can add multiple button according to your choice.
ButtonIndex=0 is used for CancelButtonTitle that is already described.
Furthor User defined Indexes start from 1 to your choice of end button.

Lets us look up about code with dismiss method:

 -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
 {
     if (buttonIndex==1) {
         NSLog(@"Store Button run successfully");
     }
 }


Above method Run Message on Console when user click on the Store button.You can add code according to your choice like store value in string or something else.

There is one Othermethod

 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
 {
     if (buttonIndex==1) {
         NSLog(@"Store Button run successfully");
     }
 }




The difference between above two methods are that clickedButtonAtIndex run when user click on Custom Button and then automatically dismiss pop up view.But didDismissWithButtonIndex runs code when popup view Dismiss.

The work of above code run same in both written methods.

Who Studied my Above tutorial carefully think that what happens if there are two Alert View in same class or more then two.The work of didDismissWithButtonIndex method is just to run code while dismissing popup not to check which alert view is executed.

Its solution is also possible.you need to add tag number with alert view.

 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:@"ABC is Student" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Store", nil];
[alert setTag:100];  
[alert show];



Now Another AlertView is:


UIAlertView *alert2=[[UIAlertView alloc]initWithTitle:@"StudentDetail" message:@"DEF is Student Father" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Store", nil];
[alert setTag:200];  
[alert show];



Now the code will be in didDismissWithButtonIndex is:



 -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
 {
if([alertview tag]==100)
{
     if (buttonIndex==1) {
         NSLog(@"Store Button run successfully");
     }
 }
if([alertview tag]==200)
{
if(buttonIndex==1)
{
NSLog(@"Second Store button run successfully");
}
}


There are some readymade design for alert view.These are UIAlertViewPlainTextInput,UIAlertViewSecureTextInput,UIAlertViewLoginAndPasswordInput.

UIAlertViewPlainTextInput looks like:



UIAlertViewSecureTextInput:




UIAlertViewLoginAndPasswordTextInput:


Now problem arise how to fetch data from textfield in alertView.Its solution is also possible.

write below code:

 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:@"ABC is Student" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"Store", nil];
alert.alertViewStyle=UIAlertViewStyleLoginAndPasswordInput;  
[alert show];



 -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
 {
     if (buttonIndex==1) {
          UITextField *logintext=[alertView textFieldAtIndex:0];
        UITextField *passwordtext=[alertView textFieldAtIndex:1];
        NSString *storestringlogin=logintext.text;
        NSString *storestringpassword=passwordtext.text;
        NSLog(@"Store Button run successfully:\n Login:%@ \n
     Password:%@",storestringlogin,storestringpassword);
     }
 }


Final Output will be :




There is also array of TextFields on Alert View.You can invoke with Index number which textfield to store data from it.

Above Code save Data in String and Display in Console with login and Password.

You can make Custom Alert View i will go on lator on it requires more coding.

I think it is very simple code you do not need any source code.If you need source code can ask from me by mailing,comment here.

I hope you like my tutorials.Any query can mail me or comment here.

My next tutorial will be Delete row from Table View.

Sunday, 12 July 2015

Inheritance in Swift

Inheritance in Swift

Learn Objective C from here:Click Here

Learn Swift from Here:Click Here

Learn Initializers in Objective C:Click Here

Learn IOS Application Development From here:Click Here

Learn Accessory Type in IOS:Click Here

I already describe you about the inheritance in objective c if you have not studied yet Click Here.

When use of methods,properties of one class required in another class without writing it again you can inherit the another class with One class called base class in general.
Think in your mind that when reusability of code occurs then you can use inheritance just that is the inheritance it is same in all programming languages but you need to remember the syntax.

In Inheritance you are most probably familiar with two types of  classes Base Class,Derived Class or Super and Sub Class Respectivelly.


What is Super and Sub Class?

Sub Class: Sub class is also called derived class which inherit the properties,methods of super class.Sub Class Access methods from super class and override it accordingly.Overrirding comes in polymorphism i will describe it lator.

Super Class: Super Class is also called Base class from which sub class is inherited their methods,properties. 


In Objective C you need to write @interface Student:Teacher in header file for subclassing.

In Swift you need to write Class Student:Teacher

I have used the getter and setter in below project you can read it from here:Click Here
Below is Example of Inheritance in Swift:


class Teacher {
    var TeacherName:String
    var TeacherSubject:String
    init(teachername:String,teachersubject:String)
    {
        self.TeacherName=teachername
        self.TeacherSubject=teachersubject
    }
    func printTeacherName()->Void
    {
        println("The Teacher:\(TeacherName) teaches \(TeacherSubject)")
    }
}
var teacher1=Teacher(teachername: "Suraj", teachersubject: "IphoneDevelopement")
teacher1.printTeacherName()

class Student: Teacher {
    var StudentName:String
    var Physics:Float
    var Chemistry:Float
    var Math:Float
    var TotalMarks:Float
    var Percentage:Float
        {
        get
            {
                return TotalMarks/300*100
            }
        set
        {
            self.Percentage=0
        }
    }
    init(studentname:String,physics:Float,chemistry:Float,math:Float)
    {
        self.StudentName=studentname
        self.Physics=physics
        self.Chemistry=chemistry
        self.Math=math
        TotalMarks=self.Physics+self.Chemistry+self.Math
      super.init(teachername: "Suraj", teachersubject: "IphoneDevlopment")
    }
    func printStudentNameTeacher()->Void
    {
        println("The Student:\(StudentName) is Teaches by Teacher:\(TeacherName) and got Percentage is:\(Percentage)")
    }
}
var student1=Student(studentname: "John", physics: 90, chemistry: 90, math: 85)
student1.printStudentNameTeacher()




You think why i use super.init() in above Example due to the chaining in Swift Designated and Convenience .

I hope you like my tutorials. Any query can mail me or comment here.

My next tutorials will be Chaining of initialisation in swift.

Friday, 10 July 2015

Accessory Type in IOS

Accessory Type In IOS

Learn initialisers and getter and setter in Swift:Click here

Learn Objective C from here:Click here

Learn Swift From Here:Click Here

Learn IOS from Here:Click here

Learn Last tutorial of table view in IOS:Click Here

Learn from Other Site:Click Here

There are total following types of accessory view in IOS:

1.)Checkmark
2.)DetailDisclosureButton
3.)DetailButton
4.)DisclosureIndicator

Why we use Accessory Type in IOS?

Accessary View are predefined views for general Cell Structure at right hand side of cell. It is used to Access the value from Cell.
If you use Checkmark it will record all those rows which are selected. If you use Disclosure Indicator it shows you Selection of previous row and link to next table view Controller. If you use DetailDisclosureButton it shows next result in Detail View.



Lets look up each example of IOS accessory Type in IOS


For CheckMark:



For DetailButton:


For DetailDisclosureIndicator:


For DisclosureIndicator:




Have you read my last tutorial of Handling of Row Selection First Read It from here:Click here

Just modification of DidSelectRowAtIndexPath Method after 

[alert show];

write 

UITableViewCell *cell=[tableview CellForRowAtIndexPath:index path];

cell.accessoryType=UITableViewCellAccessoryCheckmark;


Just change DisclosureIndicator,DetailButton  etc. At Checkmark.

Now look up the DidSelectRowAtIndexPath method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *st=[studentdata objectAtIndex:indexPath.row];
    NSString *str=[NSString stringWithFormat:@"The name of student is:%@",st];
    
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"StudentName" message:str delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
   
}


I hope you like my tutorials.If you have any query comment here or mail me.

My Next tutorial will be Attractive Table View In IOS.








Monday, 6 July 2015

Initializers and getter,setter in Swift

Initializers and getter,setter  in Swift


Learn Objective C from here:Click here

Learn Swift from here:Click here

Learn IOS from here With Objective C:Click here


As you have read  in my last tutorials of Constants,classes,methods,objects in swift. Have you not read it: Click here

Initializers in Swift is same as Objective C like initialise the properties,variables at the time of allocation of object or creating objects.


In objective c you need to write lot of code to initialise like below:

during declaration:

@property(nonatomic,strong)NSString *studentname;
-(id)initWithName:(NSString *)StudentName;
-(void)printDetails;

during  implementation:


@synthesize studentname=_studentname;

-(id)initWithName:(NSString *)StudentName
{
self.studentname=StudentName;
}

-(void)printDetail
{
NSLog(@"The name of student is:%@",self.studentname);
}

during creating object

Student *student1=[[Student alloc]initWithName:@"Suraj"];
[student1 printDetail];


Now in Swift it is too easier just write code like below:

Have you read my last tutorials of swift of creating classes and objects or not: click here


Student.Swift

class Student
{
var studentname:String
init(StudentName:String)
{
self.studentname=StudentName
}
func printDetail()->Void
{
println("The name of student is:\(student name)")
}
}



Now create objects:

var student1=Student(StudentName:"Suraj")
student1.printDetail()




You see how easy to create object in swift.In general put in your mind that in init you are initialised property during creation.
Here studentname is property and call by self and StudentName is Arguments.


Now look for getter and setter method for computed property.It is easy to write if you have C# background where get and set keyword is used to create getter and setter methods.But do not worry you can easily learn. it is shown below:

In Objective C you  can set and get property by Automatically generated by compiler as well as according to needs.
Also in Swift same thing if you do not write anything then getter and setter method generated automatically if you want it manually you can do by following like below:



class Student
{
    var studentname:String
    init(StudentName:String,physics:Float,chemistry:Float,math:Float)
    {
        self.studentname=StudentName
        self.Physics=physics
        self.Chemistry=chemistry
        self.Math=math
        TotalMarks=self.Physics+self.Chemistry+self.Math
   
    }
    var Physics:Float
    var Chemistry:Float
    var Math:Float
    var TotalMarks:Float
    var Percentage:Float
        
        {
        get
        {
            return TotalMarks/300*100
        }
        set
        {
       self.Percentage=0
        }
    
    }
    func printDetail()->Void
    {
        println("The name Of Student is:\(studentname) and his Percentage is:\(Percentage)")
    }
}
var student1=Student(StudentName: "Suraj",physics:90,chemistry:90,math:88)
student1.printDetail()






I hope you like my tutorials.If you want to donate can pay me at above link through Paypal. 
Any query can comment here or mail me i will solve it.

My next Tutorial will be Take Deeper into the Programming of Swift with Concept of Sub Class.

Wednesday, 1 July 2015

Constants,Properties,Classes,Objects,Methods in Swift

Constants,Properties,Classes,Objects,Methods in Swift

Before you going further learn swift tutorials from here: Click here

Read Data Types in Swift from here:Click here

Learn Objective C from Here:Click here


Learn Custom Cell in Table View Using Storyboard from here:Click Here



Constants in Swift:

You have studied in my last tutorial how easy is to write variables in swift and what are the data types that a swift contain.

Now the Most important thing comes how to write constants in Swift. Do you know about constants. Constants are the permanent stored value in memory address once initialised can not be changed further.

In Objective C You need to write pointer assigning of Constants with Const keyword.

NSString *const StudentName=@"ABC";


In Swift it is written as

let StudentName="ABC"

I already describe in my last tutorial how to write Strings in swift.
If you want to learn:click Here


In Swift There is not pointer assignment.In general, Swift language has not direct assignment of pointer to memory which makes it more safer.



Properties in Swift:


Objective C has two types of file Header and implementation file.
In swift You have only one file with .Swift You need to linked with that how to write methods and properties.
As you have studied in my Objective C tutorials Properties are those backed up by instance variables. In swift Properties are not backed up with instance variables.Each Property and instance variables has only one locations in memory.

In Swift Properties are declared in same way as Variables but having variables are written in inside Methods but Properties are declared in a Class.


In Objective C Properties are written as in class interface.


@property(nonatomic,strong) NSString *firstname;

In Swift  Properties are written as:

Class ...

{


Var first name="ABC"



}



Above Property is initialised at the time of declaration.

Like Objective C You can create getter and setter methods for setting property value.


In Objective C

Getter and setter can be generated automatically by Compiler through the

@syntheisize firstname=_firstname;

In swift it is Different you can set with get and set keyword like below.
If you have  C# programming background you have seen for making Business Object Get and set methods are used to assign Value to property.

class ...

{

var firstname

{
get
{

return self.first name;
}
set 
{
self.firstname="ABC"
}
}
}

There are two types of Properties in Swift. One is Computed where you manually set getter and setter methods and other is Normal variable like properties. In computed property you need to write the data type explicitly.

Lets look a simple example of x and y numbers

class ....
{
var x=10

var y:Int
{
get
{
return (x+10)
}
set
{
x=10
}
}
}


Methods in Swift:

Methods in Objective C has very difficult remember implementation. But now in swift solve this problem just simple like function implementation of Javascript.

In objective C methods is written as

-(return type)methodsname:(datatype of first arguments)FirstArguementsName SecondArguements:(datatype of second arguments)SecondArguementName

{
//body of function
}

In Swift the method is written as:

func(keyword) function name()->returnType
{
//body of function
}

When arguments are passed then function look like

func setName(firstname:string,lastname:string)->void
{
println("The name of Student is:\(first name,last name)")
}




But in objective c you need to write

-(void)setName:(NSString *)firstname lastname:(NSString *)Lastname
{
NSLog(@"The name of student is:%@%@",first name,second name);
}





Classes in Swift:

Classes designing in Swift is Similar like Objective C .

In swift class is declared as 

class classname
{

//property 
//methods

}

In swift there is only one file with .swift extension.Implementation and Declaration is done in only one file.

Simple look up at Objective C for class declaration 

In Student.h

@interface Student:NSObject

@property(nonatomic,strong)NSString *StudentName;
-(void)printName:(NSString *)StudentName;


In Student.m

@implementation Student

@syntheisize StudentName=_StudentName;

-(void)printName:(NSString *)StudentName
{
NSLog(@"The name of student is: %@",student name);
}

In Student.swift

class Student

{
var StudentName
{
get
{
return self.StudentName
}
set
{
self.StudentName

}
func printName(studentname:String)->void
{
println("The name of student is:\(student name)")
}
}


Objects in Swift:

Creation of objects in Swift is very easy like Objective C.

In Objective C Object is created like that:

Student *student1=[[Student alloc]init];

In Swift Object is created like that:

var Objectname=classname()

var student1=Student()

Calling of methods of class can be done through simple dot operator in swift.

student1.printName()

but in Objective C it can be done through square brackets like:

[student1 printName];


I have not used init yet so above tutorials create error . So read next tutorial of initialise the property so to run this simple example.




I hope you like my this tutorials. If you have any query can mail me or comment here.

My next Tutorial will be init in Swift.