Pages

Showing posts with label xCode. Show all posts
Showing posts with label xCode. Show all posts

Wednesday, October 9, 2013

Font Family Check in Xcode



NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
    NSLog(@”Family name: %@”, [familyNames objectAtIndex:indFamily]);
    fontNames = [[NSArray alloc] initWithArray:
                 [UIFont fontNamesForFamilyName:
                  [familyNames objectAtIndex:indFamily]]];
    for (indFont=0; indFont<[fontNames count]; ++indFont)
    {
        NSLog(@” Font name: %@”, [fontNames objectAtIndex:indFont]);
    }
    [fontNames release];

}


Thursday, October 3, 2013

Hide Keyboard for presentViewController

Hi, i found an issue that if you are using presentViewController then resignFirstResponder doesn't hide the keyboard. We can follow the below method for hiding keyboard

Just write the below code and add resignFirstResponder. it should work then 
-(BOOL)disablesAutomaticKeyboardDismissal{
    return NO;

}

Tuesday, October 1, 2013

UIActionSheet Menu in Xcode


To Show a Menu Sheet like below

We have to code as below

1. First of all, we need to add <UIActionSheetDelegate> delegate in class .h file

2. Now we have to code like below

UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Image from..." delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Image Gallary", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.alpha=0.90;
actionSheet.tag = 1;
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
if ([window.subviews containsObject:self.view]) {
    [actionSheet showInView:self.view];
} else {
    [actionSheet showInView:window];

}


Wednesday, September 25, 2013

Align UIImageView Center dynamically in xCode

Suppose we have an UIImageView with name imageView and have to set this in center dynamically then we can follow the below step

[imageView setImage:[UIImage imageNamed:@"imageName.png"]];
imageView.autoresizingMask = UIViewAutoresizingNone;

imageView.contentMode = UIViewContentModeCenter;

Monday, September 23, 2013

CREATION OF IMAGE VIEW IN CIRCLE

Creation of image like below.
Image 
1. Take an UIImageView in .xib or storyboard file.
2. Link that name as you want. (Here i have taken imageView_AuthorPhoto)
Now code the below for make that in circular
imageView_AuthorPhoto.layer.masksToBounds = YES;
imageView_AuthorPhoto.layer.cornerRadius = imageView_AuthorPhoto.bounds.size.width/2;
imageView_AuthorPhoto.layer.borderWidth = 1.0;
imageView_AuthorPhoto.layer.borderColor =[UIColor colorWithRed:13/255 green:70/255 blue:131/255 alpha:1.0].CGColor;

And Set Image Accordingly
[imageView_AuthorPhoto  setImageWithURL:[NSURL   URLWithString:@"imageurl"] placeholderImage: useCache:<#(BOOL)#>];

Wednesday, September 18, 2013

Crop Image from an Image in Objective C

Here is the code to cut a piece from an Image or say UIImage

+ (UIImage *)cropImage:(UIImage *)image withArea:(CGRect)rect andScale:(int) scale{
    rect = CGRectMake(rect.origin.x*scale,
                      rect.origin.y*scale,
                      rect.size.width*scale,
                      rect.size.height*scale);
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *img = [UIImage imageWithCGImage:imageRef
                                       scale:scale
                                 orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return img;
}

UITableView update Super View from Its Cell

I fought with UITable view and found that there should be some solution to update the Super view according to the selected cell from UITableView.

So i found the following Solution

Like we have added cells in UITableView like as below

NSArray *relatedContentArray = [[NSArray alloc]initWithArray:[self.somearray allObjects]];

RelatedContentTableView *relatedContentTableView = [[RelatedContentTableView alloc]initWithFrame:CGRectMake(0.0f, 88.0f, 280.0f, 460)];

relatedContentTableView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

relatedContentTableView.dataArray = self.relatedContentArray;
self.relatedContentTableView.selectedContentType = IndiewireRelatedContentFilms;
    

[self.relatedContentTableView.tableView reloadData];

Now we have to get the selected Cell in super view, So here is the solution of this

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Article *aRelatedArticle = [self.dataArray objectAtIndex:indexPath.row];
    // article is the Varibale in SuperView Class and reloadSubviewsdata is function in Super View. TypeCasting should be like below
    ((ArticleDetailsView *)self.superview.superview).article = aRelatedArticle;

    [ ((ArticleDetailsView *)self.superview.superview) reloadSubviewsData];
}

Friday, September 13, 2013

Load Image from different Sources

Load Image from External URL

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://someimageurl/imagename.jpg"]];
    
    
UIImage *image = [[UIImage alloc] initWithData:data];
    
Load Image from Project Itself
    

UIImage *image = [UIImage imageNamed:@"Disp1.jpg"];

Thursday, September 12, 2013

Random Number Array in Objective C

Hi, i think this is a common and basic requirement for every developer in each field, to get the Random numbers in Array. I have made a function to simplify this logic in Objective C.
So here is the code if this
-(void) checkExistance:(int) max
{
    int value = [self randomNumberFrom:0 to:max];//Modify according to minimum /maximum value in Array
    int i = 0;
    for (i = 0; i < [self.numbers count]; i++)
        if ([[self.numbers objectAtIndex:i] integerValue] == value)
            break;
    
    if (i == [self.numbers count])
        [self.numbers addObject:[NSNumber numberWithInt:value]];
    if ([self.numbers count] != max)
        [self checkExistance:max];
}
- (int) randomNumberFrom: (int) minValue to: (int) maxValue
{
    int rangeValue = maxValue - minValue;
    return (arc4random() % rangeValue) + minValue;

}

You just need to call checkExistance method with passing a maximum value in this. You can modify your code for minimum and maximum as well in this. 

Now just call

[self checkExistance:6];

and you will see the result by following

for(int j = 0;j<self.numbers.count;j++)
{
    NSLog(@" %@", [self.numbers objectAtIndex:j]);

}

Monday, September 9, 2013

Attach Multiple View Controllers in a Single Storyboard


I have taken 2 UIViewControllers in a single StoryBoard like in above pic.

First View Controller (with White background in above pic) is linked with ViewController.h and Second View Controller (with Red color background) is linked with SecondVCViewController.h

Linking is done by Selecting Identity Inspector as in below pic



               ^                                                                                                 ^
For First View Controller                                                  For Second View Controller

Note: Mention Other Storyboard ID(s) in Linkage, so that linkage name could identified by below code.

Now define Button's IBAction in its respected class file.

1. Now for First View Controller action


- (IBAction)onTapSecondViewAppearBtn:(id)sender {
    SecondVCViewController *svc = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVCViewController"];
    [self presentViewController:svc animated:YES completion:nil];

}

2. Now for Second View Controller action, To remove the current View

- (IBAction)onTapFirstViewBtn:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

Wednesday, September 4, 2013

Embed Font in Objective C


Here are the Steps to embed font in Objective C

Step 1 -

Put font file inside project file and add that font in project, like in attached top Image - marked with Red square

Step 2 -

Add font in ProjectName-info.plist
By Adding "Fonts provided by application" in item 0 add the name as "FontFileName".

Step 3 -

Add following code inside some comman place of project.

#define BebasNeueFont(_size_)\
[UIFont fontWithName:@"BebasNeue" size:_size_]

Step 4 -

Now Apply font to the label or required place as follow

self.embededFont.font = BebasNeueFont(21);

Result will be shown as below


Wednesday, August 28, 2013

Animation in Xcode

Here is the global animation code in Objective C

First you need to set the position or size from stating animation 
then Write the below code to animate to its final size or origin

CGRect frameDeleteLabel = lblDeleteAccount.frame;
frameDeleteLabel.origin.y = 304;

[UIView animateWithDuration:1.2 delay:0 options:0 animations:^{
    lblDeleteAccount.frame = frameDeleteLabel;
    deleteAccountButton.frame = frameDeleteButton;
} completion:^(BOOL finished) {
}];

Monday, August 26, 2013

Check iPhone or iPad by Code in Xcode

To Check iPhone or iPad view by Code, we can check by following code


if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    // Code for iPhone View

} else {
    // Code for iPad View
}


Now to Check iPhone5 or iPhone4, we can do a check in iPhone vide code

-(Boolean)checkIphone5{
    UIScreen *screen = [UIScreen mainScreen];
    CGRect fullScreenRect = screen.bounds;
    if (fullScreenRect.size.height==568) {
        return TRUE;
    }
    else{
        return FALSE;
    }
}

and We can use this as like below


if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
{
   if ([self checkIphone5]) {

      // Code for iPhone5 View
   }
   else
   {
      // Code for iPhone 4 View
   }
else {

    // Code for iPad View
}




Tuesday, August 13, 2013

Debugging in Objective C

I found a better way description of debugging in Xcode in a site
http://www.fiveminutes.eu/debugging-objective-c-code/

So i am just pasting that site matter here, for the reference.


Xcode development environment is integrated with GDB (GNU Debugger), a cross-platform debugger supporting many languages including C/C++, Fortran and Objective C. Xcode provides user interface for tasks as managing breakpoints or inspecting variables. For all advanced tasks there is the GDB command line. Command line provides commands for controlling all aspects of program execution and data manipulation.

Most common commands are:
print - prints the variable or function result value
(gdb) print self.imageView  #show the value of imageView member
(gdb) print -[self description]  #execute [self description] and show the result
NOTE: executing code can change the state of current object or application and lead to unexpected results
po - print object, command introduced in Objective C debugging and used to print out useful information about selected object (that object can be a result of code execution, as for print). _NSPrintForDebugger method will be called on object to retrieve description. All po-able objects must implement this method.
(gdb) po -[NSString stringWithString:@"This is a test."]
This is a test.
call - calls a function or method and stores the returned result.
(gdb) call (NSString*)[NSString stringWithString:@"Another test."]
$1 = (NSString *) 0x5e21120
(gdb) po $1
Another test.
bt - show call stack
cont - continue execution
next - execute next line
step - execute next line with stepping into functions
kill - stop execution
NSLog(NSString* format, …) function is useful for printing out information in the debugger console. NSLog is useful for outputting intermediate results in algorithms or loops where breakpoint usage is not practical. From iOS 4.0 and Mac OS X 10.6 it is possible to use [NSThread callStackSymbols] to get the call stack and monitor the execution flow from code.
Applications sometimes crash because access has been made to an object that has already been freed (and memory possibly reallocated). Best practice to debug such problems is enabling zombie objects by setting the NSZombieEnabled environment variable to YES. When zombies are enabled, all deallocated objects will not be freed, but instead turned into _NSZombie objects. Latter access to a _NSZombie object will trigger a breakpoint and help in tracing the zombie’s origin. No object is freed in this mode and memory consumption can skyrocket and cause application crashing on iPhone or swapping on personal computer. CFZombieLevel environment variable can be used to fine-tune zombie behavior.
Xcode also provides static analysis tool and profiler for catching performance bottlenecks, memory leaks and all other sorts of problems.

Move View while keyboard appears

There are some cases, when you want to type in UITextField and also want to show that in screen. But keyboard hides your UITextField. You can use the following code for this


-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    
    CGRect rect = self.completeSingleView.frame;
    if (movedUp)
    {
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.completeSingleView.frame = rect;
    
    [UIView commitAnimations];
}

Now How to Use this

First of all set the <UITextFieldDelegrate> in class ".h" file and set UITextField delegate to self, Like if we have some textfield with name "loginID" then set the delegate to self like below

loginID.delegate = self;

Now use the below code, which call the upper function 

-(void)textFieldDidEndEditing:(UITextField *)sender
{
    if  (self.completeSingleView.frame.origin.y < 0)
        [self setViewMovedUp:NO];
}
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if  (self.completeSingleView.frame.origin.y >= 0)
        [self setViewMovedUp:YES];
}



Monday, August 12, 2013

Hex Color to UIColor in Xcode

How to use #FF00CC or 0xFF7620 kind of colors in UIColor, So here is the answer

First of all define a function in top, like below:


#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


Then use this as below


self.logView.backgroundColor = UIColorFromRGB(0xee8029);


Reference Taken From:
http://stackoverflow.com/questions/1560081/how-can-i-create-a-uicolor-from-a-hex-string

Saturday, August 3, 2013

Touch Detection inside Polygon Shape xCode

Suppose you have some polygon shape like the above pic and you need to find the touch inside this shape.

For this i have made my own logic from various sources and this code is as below


-(BOOL)pointInPolygon:(int)xPos andY:(int) yPos andPolyArray:(NSArray *)poly
{
    int j = poly.count - 1;
    BOOL oddNodes = false;
    for (int i = 0; i <poly.count; i++) {
        NSValue *val = [poly objectAtIndex:i];
        CGPoint pi = [val CGPointValue];
        
        val = [poly objectAtIndex:j];
        CGPoint pj = [val CGPointValue];
        
        if ((pi.y < yPos && pj.y >= yPos) ||  (pj.y < yPos && pi.y >= yPos)) {
            if (pi.x + (yPos - pi.y) / (pj.y - pi.y) * (pj.x - pi.x) <xPos) {
                oddNodes = !oddNodes;
            }
        }
        j = i;
    }
    return oddNodes;
}

In this function you just need to pass X and Y position of Touch location, with the polygon co-ordinates Array.

Now how to create a Polygon Shape Array?

Here is the solution of this, to define a Polygon Shape points

self.trackArea = [NSArray arrayWithObjects:[NSValue valueWithCGPoint:CGPointMake(412,0)],
                  [NSValue valueWithCGPoint:CGPointMake(827,0)],
                  [NSValue valueWithCGPoint:CGPointMake(210,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,768)],
                  [NSValue valueWithCGPoint:CGPointMake(0,513)],
                  
                  nil];


Now How to call, So here is that

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    if([self pointInPolygon:touchPoint.x andY:touchPoint.y andPolyArray:self.track1Area])
    {
        NSLog(@"Touch Detected for polygon");
    }
}

Add Image from URL in UIView and make clickable

I have made a sample code for this example

Step 1 - Load Image from URL

     UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"screen.png"]];

  [self.completeSingleView addSubview:imageView];

Step 2 - Now to make this clickable just use the following code

    imageView.userInteractionEnabled = YES;
   imageView.tag = 2;

Step 3 - Now to add this in any UIView. Follow the code below

     [self.completeSingleView addSubview:imageView];

Step 4- Now to detect the Image in touch began event, follow the code below


-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    UITouch *touch = [touches anyObject];
    if([touch.view tag] == 2)
        NSLog(@"Your Image is Touched");
}

Wednesday, July 31, 2013

Animate Mask in Objective C

First of all you can view my masking image logic here

View

Now If i click the screen and want to animate this mask, then we can apply the below logic


-(void)moveLayer:(CALayer*)layer to:(CGPoint)point
{
    // Prepare the animation from the current position to the new position
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.fromValue = [layer valueForKey:@"position"];
    animation.toValue = [NSValue valueWithCGPoint:point];
    animation.duration = .3;
    layer.position = point;
    
    [layer addAnimation:animation forKey:@"position"];
}

-(void)resizeLayer:(CALayer*)layer to:(CGSize)size
{
    CGRect oldBounds = layer.bounds;
    CGRect newBounds = oldBounds;
    newBounds.size = size;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    
    animation.fromValue = [NSValue valueWithCGRect:oldBounds];
    animation.toValue = [NSValue valueWithCGRect:newBounds];
    animation.duration = .3;
    layer.bounds = newBounds;    
    [layer addAnimation:animation forKey:@"bounds"];
}

- (UIImageView*) animateMaskedImage:(UIImage *)image withMasked:(UIImage *)maskImage width:(int )wd andHeight:(int )ht andSize:(CGSize)size andPosition:(CGPoint)pt {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    CALayer *mask = [CALayer layer];
    mask.contents = (id)[maskImage CGImage];
    mask.frame = CGRectMake(0, 0, wd, ht);
    //Masking Animation
    [self resizeLayer:mask to:size];
    [self moveLayer:mask to:pt];
    
    imageView.layer.mask = mask;
    imageView.layer.masksToBounds = YES;
    return imageView;
}

Now we just need to call animatedMaskedImage function in our touch event like below

        [self.imageView1 removeFromSuperview];
        self.imageView1 = [self animateMaskedImage:self.image1 withMasked:self.mask1 width:1024 andHeight:768 andSize:CGSizeMake(1024*4, 768*4) andPosition:CGPointMake(1024*2, 768*2)];
        [self.completeSingleView addSubview:self.imageView1];

Tuesday, July 30, 2013

Masking Image with a transparent PNG

Hi i have made a function in which you can pass 2 UIImages and it will mask with the transparent Image
like







- (UIImageView*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    CALayer *mask1 = [CALayer layer];
    mask1.contents = (id)[maskImage CGImage];
    mask1.frame = CGRectMake(0, 0, 1024, 768);
    imageView.layer.mask = mask1;
    imageView.layer.masksToBounds = YES;
    return imageView;
}

Its returns the UIImageView, which you can add directly in UIView. You can call this method like following:

    UIImage *image = [UIImage imageNamed:@"screenFull.png"];
    UIImage *mask = [UIImage imageNamed:@"screen_mask.png"];
    [self.completeSingleView addSubview:[self maskImage:image withMask:mask]];

Here completeSingleView is a UIView.


Reference is taken from 
http://stackoverflow.com/questions/5757386/how-to-mask-an-uiimageview