Thursday, July 28, 2011

Multiple ORDER BY in SQL Query

If you want to sort your SQL Table with multiple columns then following article will give you an idea how to go about it.

Single ORDER BY can written as follows








And it will give following result which is ordered by assigned column:








Now you want to sort status  column as well while assigned column is already sorted.. 



So In general you can have SELECT * FROM TABLE ORDER BY column1 DESC, column2 DESC


If you want to include the WHERE statement as well then  
SELECT * FROM TABLE WHERE column1 > 100 ORDER BY column1 DESC, column2 DESC

And DESC is for descending order sorting and ASC is for ascending order sorting.


Wednesday, July 27, 2011

How to draw 2D doughnut shape using QuartzCore?

You want to create a 2D figure which looks like doughnut. Use following code:




- (void)drawRect:(CGRect)rect
{
    
    float _outerRadius=350.0;
    float _innerRadius=248.0
    
    
    // Create the context
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //Make sure the remove the anti-alias effect from circle
    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);
    
    
    
    
    //orange
    float dRed=0.9f;
    float dGreen=0.38f;
    float dBlue=0.0f;
    
    float lRed=1.0f;
    float lGreen=0.61f;
    float lBlue=0.0f;
    
    
    CGContextAddArc(context, _outerRadius/2, _outerRadius/2, _outerRadius/2, 0, 360, 0);
    CGContextClip(context);
    
    //Create the gradient
    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { lRed, lGreen, lBlue, 0.9 ,   // Start color
        dRed, dGreen, dBlue, 0.9}; // Mid color and End color
    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    
    //Draw the gradient
    CGPoint start = CGPointMake(0,self.center.y); 
    CGPoint end = CGPointMake(_outerRadius,self.center.y);
    CGContextDrawLinearGradient(context, glossGradient, start, end, kCGGradientDrawsBeforeStartLocation);
    
    //Draw the hole to make it look like doughnut
    CGContextSetFillColorWithColor( context, [UIColor whiteColor].CGColor );
    CGContextSetBlendMode(context, kCGBlendModeClear);
    CGRect holeRect= CGRectMake((_outerRadius-_innerRadius-2)/2, (_outerRadius-_innerRadius-2)/2, _innerRadius+1, _innerRadius+1);
    CGContextFillEllipseInRect( context, holeRect );
    
    
}





This code will make a doughnut as shown in following screenshot. (Please ignore the check texture in the background of screenshot, that will not be generated with above code, Only orange doughnut will be generated). You can use your own created gradient by changing the values in gradient.




How to add various kinds of UIGesturesRecognizer to your view?

       UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
    [piece addGestureRecognizer:rotationGesture];
    [rotationGesture release];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
    [pinchGesture setDelegate:self];
    [piece addGestureRecognizer:pinchGesture];
    [pinchGesture release];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [panGesture setDelegate:self];
    [piece addGestureRecognizer:panGesture];
    [panGesture release];
    
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [piece addGestureRecognizer:longPressGesture];
    [longPressGesture release];







For more details..you can refer to Apple' Sample code called Touches.


Note: Writing blog after so long.. I was so busy travelling... hardly had any time on hand.. but now its getting better, I will have more time on hand to blog.

Thursday, July 14, 2011

How to add blue NavigationBar button ? (programmatically)


You want to add a button looking like this on your navigationBar.

Courtesy


    UIButton *confirmSButton = [UIButton buttonWithType:102]; 
    [confirmSButton addTarget:self action:@selector(confirmButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [confirmSButton setTitle:@"Confirm" forState:UIControlStateNormal];
    UIBarButtonItem  *button = [[UIBarButtonItem alloc] initWithCustomView:confirmSButton];
    navBar.rightBarButtonItem = button;
    
    
    


Where navBar is navigationBar.


More Information HERE and HERE about numbers like 101,102, 103.

How to add UISegmentControl to UIToolBar ? (programmatically)

Here is the code snippet. Toolbar is the UIToolBar, This  where you want to add your segmentBar.This code also gives you an idea about using  spaces between toolbar items.

      UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshClicked:) ];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    NSArray *statusItems = [[NSArray alloc] initWithObjects:@"Girls",@"Boys", nil];
    UISegmentedControl *bottomSegmentBar = [[UISegmentedControl alloc] initWithItems:statusItems];
    bottomSegmentBar.segmentedControlStyle=UISegmentedControlStyleBar;
    [bottomSegmentBar addTarget:self action:@selector(segmentBarClicked:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *SegmentItem = [[UIBarButtonItem alloc] initWithCustomView:bottomSegmentBar];              
    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:flex,SegmentItem,flex,refresh,nil];
    Toolbar.items = toolbarItems;









Sunday, July 10, 2011

iPhone - Rotation with a single touch or finger

Code Snippet for rotating a view with single finger.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    touch1=[touch locationInView:self.superview];
    touch2=[touch previousLocationInView:self.superview];

    
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    UITouch *touch = [touches anyObject];
    CGPoint currentTouch1=[touch locationInView:self.superview];
    CGPoint currentTouch2=[touch previousLocationInView:self.superview];

    
    CGFloat previousAngle = atan2(touch2.y - touch1.y, touch2.x - touch1.x) * 180 / 3.14;
    CGFloat currentAngle = atan2(currentTouch2.y - currentTouch1.y,currentTouch2.x - currentTouch1.x) * 180 / 3.14;
    
    CGFloat angleToRotate = currentAngle - previousAngle;
    
    CGAffineTransform transform = CGAffineTransformRotate(self.transform, angleToRotate*3.14/180);
    
    self.transform = transform;
    touch1 = currentTouch1;
    touch2 = currentTouch2;
    
    
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

Find User's Language in iPhone

If you are writing an application where you want to know what language is set in user's setting, then you can use following code snippet. This will give you an idea how to check for any other language, this code only checks for German and English.

              NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
    
    if([currentLanguage compare:@"de"] == NSOrderedSame
        NSLog(@"Its German");
    else if([currentLanguage compare:@"en"] == NSOrderedSame
        NSLog(@"Its English");

Friday, July 8, 2011

Draw Radial Gradient in Quartz

Here is the code snippet for that to be written inside - (void)drawRect:(CGRect)rect of UIView




    CGContextRef ctx = UIGraphicsGetCurrentContext();

    
    
    //Draw the gray Gradient
    
    CGFloat BGLocations[2] = { 0.0, 1.0 };
    CGFloat BgComponents[8] = { 0.25, 0.25, 0.25 , 1.0// Start color
       0.11, 0.11, 0.11, 1.0 }; // Mid color and End color
    CGColorSpaceRef BgRGBColorspace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef bgRadialGradient = CGGradientCreateWithColorComponents(BgRGBColorspace, BgComponents, BGLocations, 2);
    
    
    CGPoint startBg = CGPointMake(250, 250); 
    CGFloat endRadius= 250;
    
    
    CGContextDrawRadialGradient(ctx, bgRadialGradient, startBg, 0, startBg, endRadius, kCGGradientDrawsAfterEndLocation);
    CGColorSpaceRelease(BgRGBColorspace);
    CGGradientRelease(bgRadialGradient);
    







Screenshot of the output

Monday, July 4, 2011

3D shapes and Rotation in Opengl ES 2.0

It will be helpful to go through Previous tutorial before reading this one. LINK

Now, we will change the structure of Vertex a little. Position array is now of size 3 to handle x, y as well as z.


struct Vertex {
    float Position[3];
    float Color[4];
};



Our rotation matrix
void ApplyRotationX(float degrees)
{
    float radians = degrees * 3.14159f / 180.0f;
    float s = std::sin(radians);
    float c = std::cos(radians);
    float zRotation[16] = {
        1, 0, 0, 0,
        0, c, s, 0,
        0, -s, c, 0,
        0, 0, 0, 1
    };
    
    GLint modelviewUniform = glGetUniformLocation(buildProgram, "Modelview");
    glUniformMatrix4fv(modelviewUniform, 1, 0, &zRotation[0]);
}

void ApplyRotationY(float degrees)
{
    float radians = degrees * 3.14159f / 180.0f;
    float s = std::sin(radians);
    float c = std::cos(radians);
    float zRotation[16] = {
        s, 0, c, 0,
        0, 1, 0, 0,
        c, 0, -s, 0,
        0, 0, 0, 1
    };
    
    GLint modelviewUniform = glGetUniformLocation(buildProgram, "Modelview");
    glUniformMatrix4fv(modelviewUniform, 1, 0, &zRotation[0]);
}

void ApplyRotationXY(float degrees)
{
    float radians = degrees * 3.14159f / 180.0f;
    float s = std::sin(radians);
    float c = std::cos(radians);
    float zRotation[16] = {
        s, 0, c, 0,
        s*c, c, -s* s, 0,
        c*c, -s, -c * s, 0,
        0, 0, 0, 1
    };
    
    GLint modelviewUniform = glGetUniformLocation(buildProgram, "Modelview");
    glUniformMatrix4fv(modelviewUniform, 1, 0, &zRotation[0]);
}




Arrays of vertex and indices

// Define the positions and colors(R,G,B,A) of 8 vertices of square.
const Vertex Vertices[] = {
    {{0, 0, 0}, {1, 0, 0, 1}},
    {{0, 0.5, 0},  {0, 1, 0, 1}},
    {{0.5, 0.5, 0},  {1, 1, 0, 1}},
    {{0.5, 0, 0}, {1, 0, 1, 1}},
    {{0, 0, 0.5}, {0, 1, 1, 1}},
    {{0, 0.5, 0.5},  {0, 0.5, 0, 1}},
    {{0.5, 0.5, 0.5},  {0.5, 0.5, 0, 1}},
    {{0.5, 0, 0.5}, {0.5, 0, 0.5, 1}},
  
};

//Define the order of vertices for 12 triangles/
//0,1,2 forms first triangle
//2,3,0 form second triangle.
const GLubyte Indices[] = {
    0, 1, 2,
    2, 3, 0,
    4,5,6,
    6,7,4,
    0,1,4,
    1,4,5,
    1,2,6,
    1,5,6,
    2,3,6,
    3,6,7,
    0,3,4,
    3,4,7,
    
};


And finally drawing

       // Drawing code
    glClearColor(1.0f, 1.0f, 1.0f, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    
    switch (rotateAlong) {
        case 1:
            ApplyRotationX(degreesX);
            break;
        case 2:ApplyRotationY(degreesY);
            break;
        default:ApplyRotation(degreesZ);
            break;
    }
    
    
    
    
    glEnableVertexAttribArray(_positionSlot);
    glEnableVertexAttribArray(_colorSlot);
    
    
    //Lets give these functions pointer to head of vertex array.
    GLsizei stride = sizeof(Vertex);
    const GLvoid* pCoords = &Vertices[0].Position[0];
    const GLvoid* pColors = &Vertices[0].Color[0];
    
   //Attribute changed from 2 (when we had drawn square) to 3 (dealing with cube x,y and z)
    glVertexAttribPointer(_positionSlot, 3, GL_FLOAT, GL_FALSE, stride, pCoords);
    glVertexAttribPointer(_colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
    
    //Draw the 12 triangles and (12*3=)36 indices.
    const GLvoid* bodyIndices = &Indices[0];
    glDrawElements(GL_TRIANGLES,12* 3, GL_UNSIGNED_BYTE, bodyIndices);
    
    glDisableVertexAttribArray(_positionSlot);
    glDisableVertexAttribArray(_colorSlot);    
    
    [mimContext presentRenderbuffer:GL_RENDERBUFFER];


In order to know about rotation matrix, read this LINK
It tells you about matrix used for rotation around x, y and z axis. For rotation around X as well Y (mixed rotation) we just multiply rotation matrix of X and Y axis.

There are 3 sliders with which  you can rotate the cube along X, Y and Z axis.

     //Solo Rotation along either of X,Y or Z.
    switch (rotateAlong) {
        case 1:
            ApplyRotationX(degreesX);
            break;
        case 2:ApplyRotationY(degreesY);
            break;
        default:ApplyRotation(degreesZ);
            break;
    }


    //Comment above lines in switch in code
    //Uncomment following lines to see mixed rotation.
    //Mixed Rotation along X and Y
    ApplyRotationXY(40);
    

Check out screenshot:
















You can download the code HERE

Localization of nib file.

Ok. In previous we post we talked about how to get the localized string values on your .m files. LINK.

In this post, we will talk about how to localize the strings present in the nib file.

One way would be to make the connections of all the elements in the view and then set their title text with NSLocalizedString(@"key", @""); .Sometimes this is the only way to do it when the text in the nib files are dynamic.

Next way(For static strings in the nib files), recommended by Apple is following. We have created a nib file for us. And it looks like following.



























Because it is in english, we will put in en.lproj directory.

















 Now we open Terminal to write some commands to extract the english strings from our nib file into a new string file. By using cd I am inside the Localization folder. Following is my dir structure seen on Finder window.
















I write following command in Terminal window to extract strings file.





ibtool --generate-strings-file en.lproj/HomeController.strings en.lproj/HomeController.xib





(Note: the command above will generate the HomeController.strings file in en.lproj  folder, you will have to add it in your Xcode yourself manually ) HomeController.strings  string file which looks like following:












We create the copy of  HomeController.strings in de.lproj folder and replace the english strings with german strings. Manually add it in Xcode. 
HomeController.strings  string file which looks like following:



































Now we will create the  german version of the nib file by merging the german string file (I mean : de.lproj> HomeController.strings) with original nib file by using following command


ibtool --strings-file de.lproj/HomeController.strings --write de.lproj/HomeController.xib en.lproj/HomeController.xib

This  will generate german translated nib file in de.lproj folder. You add it manually in your Xcode. It looks like following:
Now we just add the HomeController in our window and run the app. You will english version of nib file when language of device is english and german when language of device is set as german.


Download the code HERE

In case, you want to know How to change Language in Simulator. LINK