Tuesday 4 August 2015

Convert UIView to UIImage. Taking screenshot programatically iOS.

-(UIImage *)convertViewToImage:(UIView*)view
{
    UIGraphicsBeginImageContext(view.bounds.size);//context create a canvas to draw 
    [view drawViewHierarchyInRect: view.bounds afterScreenUpdates:YES];//draws the view hierarchy into the current context
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();//Fetches UIImage from the current context
    UIGraphicsEndImageContext();// Context ends.
 
    return image;
}

Friday 31 July 2015

Increase button hit area by changing the Edge Inset. UIButton with UIEdgeInsetsMake.

#import <objc/runtime.h>

@implementation UIButton (Extensions)

@dynamic hitTestEdgeInsets;

static const NSString *KEY_HIT_TEST_EDGE_INSETS = @"HitTestEdgeInsets";

-(void)setHitTestEdgeInsets:(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = [NSValue value:&hitTestEdgeInsets withObjCType:@encode(UIEdgeInsets)];
    objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIEdgeInsets)hitTestEdgeInsets {
    NSValue *value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS);
    if(value) {
        UIEdgeInsets edgeInsets; 
       [value getValue:&edgeInsets]; 
       return edgeInsets;
    }else {
        return UIEdgeInsetsZero;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets, UIEdgeInsetsZero) ||       !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets);
    
    return CGRectContainsPoint(hitFrame, point);
}


@end



Usage-

 _backBtn = [[UIButton alloc]initWithFrame:CGRectMake(16, 12, 28, 28)];    
    [_backBtn setBackgroundImage:[UIImage imageNamed:@"backphoto"] forState:UIControlStateNormal];
    [_backBtn addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [_backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-15, -15, -15, -15)];//increase the hit area of button by 15 on all sides top,left,bottom,right


Monday 22 June 2015

Pass or associate id (any object) with NSObject(UIView,UIAlertView, etc). Add string Tags to NSObject.

Create a category of NSObject Class

.h

#import <Foundation/Foundation.h>

#import <objc/runtime.h>

#pragma mark - NSObject

@interface NSObject (CCFoundation)

- (id)associativeObjectForKey: (NSString *)key;
- (void)setAssociativeObject: (id)object forKey: (NSString *)key;

@end




.m

#pragma mark - NSObject

@implementation NSObject (CCFoundation)

static char associativeObjectsKey;

- (id)associativeObjectForKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    return [dict objectForKey: key];
}

- (void)setAssociativeObject: (id)object forKey: (NSString *)key {
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &associativeObjectsKey);
    if (!dict) {
        dict = [[NSMutableDictionary alloc] init];
        objc_setAssociatedObject(self, &associativeObjectsKey, dict, OBJC_ASSOCIATION_RETAIN);
    } [dict setObject: object objectForKey: key];
}


@end


-------------------:USAGE:-----------------

UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"title" message:@"alert" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];

// Associate MyObject(of type id) with a key
[alertView setAssociatedObject:MyDict forKey:@"kKeyResponse"];
alertView.tag = KTagAlert;
[alertView show];



#pragma mark- Alert View Delegate-
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (alertView.tag == KTagNotificationAlert) {

// Fetch the associated object(id) currently dictionary 
   NSMutableDictionary *associatedObjectDict = [alertView associativeObjectForKey:@"kKeyResponse"];
NSLog(@"%@", associatedObjectDict);
        if (associatedObjectDict) {
            //Valid
            switch (buttonIndex) {
                case 0:{// cancel pressed
                    break;
                }
                case 1: {// ok pressed
                    break;
                }
                default:
                    break;
            }
        }
        else{
            [[[UIAlertView alloc]initWithTitle:@"Error" message:@"Please try later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }
    }
}





1. Refer Link
2. Refer Link 

Friday 3 April 2015

Replace Null, , (null) , nil , NSNull, Values from NSString with empty string @""



+(NSString*)replaceNullValuesWithEmptyString:(id)tempObj
{
    if (([tempObj isKindOfClass:[NSNull class]])||
        (tempObj == nil) ||
        (tempObj == (id)[NSNull null])||
        [tempObj isEqual:[NSNull null]] ||
        [tempObj isEqual:nil]) {
    }
    else {
        if([tempObj respondsToSelector:@selector(isEqualToString:)]) {
            if ([tempObj isEqualToString:@"<null>"] ||
                [tempObj isEqualToString:@"(null)"]) {
            }
            else {
                if ([tempObj respondsToSelector:@selector(length)]) {
                    if ([tempObj length]>0) {
                         NSLog(@"Check Passed.");
                        return tempObj;
                    }
                }
            }
        }
    }
    NSLog(@"Check failed.");
    return @"";

}

Wednesday 18 March 2015

NSAttributedString with fonts, paragraph Style, line spacing using NSMutableAttributedString

// create a Attributed string and adding different parameters like font, paragraph Style, etc

    // Create UIFont -
    UIFont *systemFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:17.0];

    // Create a paragraphStyle -
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.maximumLineHeight = 45;
    paragraphStyle.minimumLineHeight = 30;
    paragraphStyle.lineSpacing = 15;
    paragraphStyle.lineHeightMultiple = 10;
    
    // create a dictionary of Attributed -
    NSDictionary * fontAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:systemFont,  NSFontAttributeName,NSParagraphStyleAttributeName,paragraphStyle, nil];
    
    // create a Attributed  string and adding parameters dictionary-
    NSMutableAttributedString *libTitle = [[NSMutableAttributedString alloc] initWithString:@"Hello there, \n" attributes:fontAttributes];
    

    // create second Attributed  string with different font-
    UIFont *subTextFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:15.0];

    NSDictionary * subTitlefontAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:subTextFont, NSFontAttributeName,, nil];

    NSMutableAttributedString *subTitleString = [[NSMutableAttributedString alloc] initWithString:@"MacOS & iOS developments tips" attributes: subTitlefontAttributes];
    

    // Append Attributed string and create a single string-
    [libTitle appendAttributedString: subTitleString];

    // Set Attributed
 string on the label
    [self.myLabel setAttributedText:libTitle];



    

Thursday 29 January 2015

Programmatically trigger UIButton action . Calling Method from button @selector.

- (void)sendActionsForControlEvents:(UIControlEvents)controlEvents

Parameters:  controlEvents 
A bitmask whose set flags specify the control events for which action messages are sent. See Control Events for bitmask constants.
Description:Sends action messages for the given control events.UIControl implements this method to send all action messages associated with controlEvents, 
repeatedly invoking sendAction:to:forEvent: in the process. 
The list of targets and actions it looks up is constructed from prior invocations of addTarget:action:forControlEvents:.


Eg:
To call a method  MySecretMethod in newViewController 
[newViewController.button  addTarget: self 
                                              action@selector (MySecretMethod)  
                                              forControlEvents:  UIControlEventTouchUpInside];


Method 1: declare MySecretMethod in .h of newViewController and call it
 by its object (so it wont be secret as can be accessed from anywhere.)
                 [newViewController MySecretMethod];

Method 2: declare button in .h of newViewController and call button action using following statement
[newViewController.button sendActionsForControlEventsUIControlEventTouchUpInside];


Looping SuperView 
You can add or change the button action by looping superview view using addTarget:action:forControlEvents:
for(UIButton *aButton in self.view.subviews){
        if([aButton isKindOfClass:[UIButton class]]){
            [aButton addTarget: self 
                     action:@selector(buttonClick:) 
                     forControlEvents: UIControlEventTouchUpInside];
             }
    }


Read More: