Sunday, 25 January 2015

UITextView Auto height

[textview sizeToFit];
[textview.textContainer setSize:textview.frame.size];

UILabel auto height

.h

 @interface ViewController : UIViewController {

    IBOutlet UILabel *label;

   }

.m

 - (void)viewDidLoad {
   [super viewDidLoad];

 //  UILabel *label = [[UILabel alloc] init];
   label.backgroundColor = [UIColor lightGrayColor];

   NSString *lorum = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.";

   //for use labrect with UITextView you set the font of UITextView:
   //label.font = [UIFont systemFontOfSize:17];      

   CGSize maxSize = CGSizeMake(320, 410);
   CGRect labrect = [lorum boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:Nil];

   label.text = lorum;
   //for use UITextView you should comment the line under
   label.numberOfLines = 0;
   label.frame = CGRectMake(0, 30, 320, labrect.size.height);

 //  [self.view addSubview:label];

  };

Saturday, 24 January 2015

Integer value pass one UIViewController1 to another UIViewController2


ViewController1


 NSInteger theInteger = 108;

   ViewController2 *pass = [[ViewController2 alloc]init];
    [pass setMyInteger:theInteger];
    [self.navigationController pushViewController: pass animated:YES];


ViewController2

@property(nonatomic) NSInteger myInteger;

Friday, 23 January 2015

ARC

#if !__has_feature(objc_arc)
#error This class requires automatic reference counting

#endif

Thursday, 22 January 2015

UITableViewCell selection with Custom height

 cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        // change background color of selected cell
        UIGraphicsBeginImageContextWithOptions(cell.bounds.size, NO, 0);
        // change this color as you like
        [[UIColor  colorWithRed:(80.0f/255.0f) green:(170.0f/255.0f) blue:(57.0f/255.0f) alpha:1.0f] setFill];
        // fiddle with this size as you like
        [[UIBezierPath bezierPathWithRect:CGRectMake(0,0,cell.contentView.frame.size.width, 140)] fill];
        [UIBezierPath bezierPathWithRoundedRect:cell.selectedBackgroundView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20.0f, 0.0f)];
        UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        UIImageView* iv = [[UIImageView alloc] initWithImage:im];
        // rounded = nil;
        cell.selectedBackgroundView = iv;

Separate digits in an NSString to display a phone number

NSString *tenDigitNumber = @"1234567890";
tenDigitNumber = [tenDigitNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d{4})"
                                                           withString:@"$1-$2-$3"
                                                              options:NSRegularExpressionSearch
                                                                range:NSMakeRange(0, [tenDigitNumber length])];
NSLog(@"%@", tenDigitNumber);

Creating Custom UIProgressView

Now, Lets create/add a New Objective -C Class in your project. Now, in your header file make it a subclass of UIProgressView.

@interface CustomProgressView : NSObject  --> @interface CustomProgressView : UIProgressView
your .h file : //  CustomProgressView.h

#import <UIKit/UIKit.h>
@interface CustomProgressView : UIProgressView
@end

Now, in .m file, we will be using two images in DrawRect: method to redraw new Progress View.
your .m file :

 //  CustomProgressView.h
- (void)drawRect:(CGRect)rect {
   // lets prepare UIImage first, with stretching to fit our requirements
    UIImage *background = [[UIImage imageNamed:@"progress-bar-bg.png"]    
                           resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 4)];
    UIImage *fill = [[UIImage imageNamed:@"progress-bar-fill.png"]    
                     resizableImageWithCapInsets:UIEdgeInsetsMake(0, 5, 0, 4)];

    // Draw the background in the current rect with background UIImage
    [background drawInRect:rect];

    // Compute the max width in pixels for the fill.  Max width being how
     wide the fill should be at 100% progress. (maximun fill width)
    NSInteger maxWidth = rect.size.width;

   // here we are filling whole width of ProgressView
    // Compute the width for the current progress value, 0.0 - 1.0 corresponding
       to 0% and 100% respectively.
    NSInteger curWidth = floor([self progress] * maxWidth);

   //[self progress] gives the current progress rate of UIprogressView
   // floor returns absolute integer
    // Create the rectangle for our fill image accounting for the position offsets,
      resizing the filling image rect to cover the background
      (adjust as per your design, like from where you want to start fill,
     where you want to end, how many pixel you want to left in upper side etc)
    CGRect fillRect = CGRectMake(rect.origin.x,
                                 rect.origin.y+1,
                                 curWidth,
                                 rect.size.height-2);

    // Draw the fill
    [fill drawInRect:fillRect];
}

That's all in our UIProgressView class.Now, you can use this UIProgressView  by calling initWIthFrame: method from any other UIView or UIViewController and you can have any size as images are stretchable.  Let's call it from some other UIView where we need UIProgressView:

UIView *v = [[UIView alloc] initWithFrame:CGRectMake(20, 281, 260, 33)];
 v.backgroundColor = [UIColor darkGrayColor];//creating back view for UIprogress, Don't use it if you are going to display only UIProgressView
   UIProgressView* progressTest = [[CustomProgressView alloc] initWithFrame:CGRectMake(5, 9, 250, 15)];//CGRectMake(25, 290, 250, 15)
    progressTest.progress = 0.1;
    [v addSubview:progressTest];
    [self.view addSubview:v]; // That's all we need to do

  // for demo, increasing progress using NStimer
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startProgressing) userInfo:nil repeats:YES];
}

-(void) startProgressing {
    float t = progressTest.progress;
    progressTest.progress = t + 0.1;
}

2 IMAGES:



Thursday, 15 January 2015

Change frame programmatically with auto layout

1. Create a height constarint for your view in your interface.
2. Then add an IBOutlet object in your class for this constraint. for example,

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint;



Connect this object in your connection panel.

3. Then change the value of this constraint whenever you needed

 self.heightConstraint.constant = 40;

Tuesday, 6 January 2015

How to pass UITableView IndexPath to UIButton @selector by parameters in iOS?

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(10.0, 2.0, 140.0, 40.0)];
[btn setTitle:@"ButtonTitle" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[btn setTag:indexPath.row];
[cell.contentView addSubview:btn];

-(void)buttonClicked:(id)sender
{
    NSLog(@"tag number is = %d",[sender tag]);
    //In this case the tag number of button will be same as your cellIndex.
   // You can make your cell from this.

   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[sender tag] inSection:0];
   UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];
}

Note: Above solution will work when your tableView has only 1 section. If your tableView has more than one section either you should know your section index or go for below methods.

Alternative:1

UIView *contentView = (UIView *)[sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [tblView indexPathForCell:cell];

UIView *contentView = (UIView *)[sender superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [tblView indexPathForCell:cell];

Alternative:2

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
UITableViewCell *cell = [tblView cellForRowAtIndexPath:indexPath];

Monday, 5 January 2015

How to copy one NSMutablearray to another NSMutablearray?

[arr1 initWithObjects:@"1",@"2", nil];
arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];

Sorting NSMutableArray

  NSMutableArray *myColors = [NSMutableArray arrayWithObjects: @"red", @"green", @"blue", @"yellow", nil];
    
    NSArray *sortedArray;
    
    sortedArray = [myColors sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    

    myColors = [NSMutableArray arrayWithArray:sortedArray];

Friday, 2 January 2015

Remove white space from contact number fetched from phone book


NSString * strippedNumber = [stringName stringByReplacingOccurrencesOfString:@"[^+0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [stringName length])];