Resize table cell according to text length

Some times we need to customize our table cell’s height according to text length. For long text we need to make a bigger cell and vice versa. Here is the method to do this:

1. define you table cell’s size and font:

#define CONST_Cell_height 50.0f
#define CONST_Cell_width 270.0f
#define CONST_textLabelFontSize     16
#define CONST_detailLabelFontSize   14

2. Here is the method to calculate table cell width:

– (int) heightOfCellWithTitle :(NSString*)titleText
andSubtitle:(NSString*)subtitleText
{
CGSize titleSize = {0, 0};
CGSize subtitleSize = {0, 0};

if (titleText && ![titleText isEqualToString:@””])
titleSize = [titleText sizeWithFont:[UIFont boldSystemFontOfSize:16]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];

if (subtitleText && ![subtitleText isEqualToString:@””])
subtitleSize = [subtitleText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];

descriptionLabelHeight = subtitleSize.height;

return titleSize.height + subtitleSize.height;
}

3. Use this in your table height for row:

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

NSString *title = @”Yor cell title”;
NSString *subtitle =@”Your cell subtitle”;

int height =  “some constant” + [self heightOfCellWithTitle:title andSubtitle:subtitle]; // some constant is used to adjust cell height. may be zero.

return (height < CONST_Cell_height ? CONST_Cell_height : height);

}

it will resize the table cell according to text size.

!! Enjoy !!

Masking of Image on another image

Here is a small core graphics method for masking of images:

 

– (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

CGContextRef mainViewContentContext;
CGColorSpaceRef colorSpace;

colorSpace = CGColorSpaceCreateDeviceRGB();

// create a bitmap graphics context the size of the image
mainViewContentContext = CGBitmapContextCreate (NULL, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

// free the rgb colorspace
CGColorSpaceRelease(colorSpace);

CGImageRef maskingImage = [maskImage CGImage];
CGContextClipToMask(mainViewContentContext, CGRectMake(0, 0, maskImage.size.width, maskImage.size.height), maskingImage);
CGContextDrawImage(mainViewContentContext, CGRectMake(0, 0, image.size.width, image.size.height), self.CGImage);

// Create CGImageRef of the main view bitmap content, and then
// release that bitmap context
CGImageRef mainViewContentBitmapContext = CGBitmapContextCreateImage(mainViewContentContext);

// convert the finished resized image to a UIImage
UIImage *theImage = [UIImage imageWithCGImage:mainViewContentBitmapContext];
// image is retained by the property setting above, so we can
// release the original

CGContextRelease(mainViewContentContext);
CGImageRelease(mainViewContentBitmapContext);
maskingImage = nil;
CGImageRelease(maskingImage);
// return the image
return theImage;

}

For more detail about masking please checkout Quartz 2D developer guide:

http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html

 

!! Enjoy !!

Limiting Zoom level in UIPinchGestureRecognizer

Sometimes when we are zooming image by using Pinch Gesture, we can’t handle the size of zooming. Here is a small code to do this.

The code below assumes there is an instance variable CGFloat lastScale and that a view has been set for the UIPinchGestureRecognizer.

– (void)handlePinchGesture:(UIPinchGestureRecognizer *)gestureRecognizer {

if([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
// Reset the last scale, necessary if there are multiple objects with different scales
lastScale = [gestureRecognizer scale];
}

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
[gestureRecognizer state] == UIGestureRecognizerStateChanged) {

CGFloat currentScale = [[[gestureRecognizer view].layer valueForKeyPath:@”transform.scale”] floatValue];

// Constants to adjust the max/min values of zoom
const CGFloat kMaxScale = 2.0;
const CGFloat kMinScale = 1.0;

CGFloat newScale = 1 –  (lastScale – [gestureRecognizer scale]); // new scale is in the range (0-1)
newScale = MIN(newScale, kMaxScale / currentScale);
newScale = MAX(newScale, kMinScale / currentScale);
CGAffineTransform transform = CGAffineTransformScale([[gestureRecognizer view] transform], newScale, newScale);
[gestureRecognizer view].transform = transform;

lastScale = [gestureRecognizer scale];  // Store the previous scale factor for the next pinch gesture call
}
}

!! Enjoy !!

Customize TabBar in iPhone

When you add Tab Bar in your iPhone project, by default its background color is black and selection color is blue. But if you need to change it add these code in your project file RootViewController-

// RootViewController.h file

@interface UITabBar (ColorExtensions)

– (void)recolorItemsWithColor:(UIColor *)color shadowColor:(UIColor *)shadowColor shadowOffset:(CGSize)shadowOffset shadowBlur:(CGFloat)shadowBlur;

@end

@interface UITabBarItem (Private)

@property(retain, nonatomic) UIImage *selectedImage;

– (void)_updateView;

@end

//RootViewController.m file

@implementation UITabBar (ColorExtensions)

– (void)recolorItemsWithColor:(UIColor *)color shadowColor:(UIColor *)shadowColor shadowOffset:(CGSize)shadowOffset shadowBlur:(CGFloat)shadowBlur

{

CGColorRef cgColor = [color CGColor];

CGColorRef cgShadowColor = [shadowColor CGColor];

for (UITabBarItem *item in [self items])

if ([item respondsToSelector:@selector(selectedImage)] &&

[item respondsToSelector:@selector(setSelectedImage:)] &&

[item respondsToSelector:@selector(_updateView)])

{

CGRect contextRect;

contextRect.origin.x = 0.0f;

contextRect.origin.y = 0.0f;

contextRect.size = [[item selectedImage] size];

// Retrieve source image and begin image context

UIImage *itemImage = [item image];

CGSize itemImageSize = [itemImage size];

CGPoint itemImagePosition;

itemImagePosition.x = ceilf((contextRect.size.width – itemImageSize.width) / 2);

itemImagePosition.y = ceilf((contextRect.size.height – itemImageSize.height) / 2);

UIGraphicsBeginImageContext(contextRect.size);

CGContextRef c = UIGraphicsGetCurrentContext();

// Setup shadow

CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);

// Setup transparency layer and clip to mask

CGContextBeginTransparencyLayer(c, NULL);

CGContextScaleCTM(c, 1.0, -1.0);

CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);

// Fill and end the transparency layer

CGContextSetFillColorWithColor(c, cgColor);

contextRect.size.height = -contextRect.size.height;

CGContextFillRect(c, contextRect);

CGContextEndTransparencyLayer(c);

// Set selected image and end context

[item setSelectedImage:UIGraphicsGetImageFromCurrentImageContext()];

UIGraphicsEndImageContext();

// Update the view

[item _updateView];

}

}

@end

// in ViewDidLoad{

// Give the selection color and its shadow

[[[self tabBarController] tabBar] recolorItemsWithColor:[UIColor whiteColor] shadowColor:[UIColor blackColor] shadowOffset:CGSizeMake(0.0f, -1.0f) shadowBlur:3.0f];

}

It’s works great friends 🙂

!! Enjoy !!

Great help for NSCalendar..

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];

[components setHour:-[components hour]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);

[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];

components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]];

[components setDay:([components day] – ([components weekday] – 1))];
NSDate *thisWeek = [cal dateFromComponents:components];

[components setDay:([components day] – 7)];
NSDate *lastWeek = [cal dateFromComponents:components];

[components setDay:([components day] – ([components day] -1))];
NSDate *thisMonth = [cal dateFromComponents:components];

[components setMonth:([components month] – 1)];
NSDate *lastMonth = [cal dateFromComponents:components];

NSLog(@”today=%@”,today);
NSLog(@”yesterday=%@”,yesterday);
NSLog(@”thisWeek=%@”,thisWeek);
NSLog(@”lastWeek=%@”,lastWeek);
NSLog(@”thisMonth=%@”,thisMonth);
NSLog(@”lastMonth=%@”,lastMonth);

Creating UIColor objects from hex values

It’s pretty inconvenient to create UIColor objects while developing apps for the iPhone, as you need to specific separate values for the RGB parts: red, green, blue.
I found a trick online a few weeks ago on how to automatically generate that code, by simply using a mac
#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]

The usage looks something like this:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

if (nil == cell) {

cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease];

}

cell.textColor = UIColorFromRGB(0x333333);

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

cell.text = @"Testing 1 2 3";

}

How to add Three20 into your project

  • Source: Download the Three20 source.
  • Three20 is compiled as a static library and the easiest way to add it to your project is to use Xcode’s “dependent project” facilities. Here’s how:
  • Clone the Three20 git repository:
    git clone git://github.com/facebook/three20.git
  • Locate the “Three20.xcodeproj” file under “Three20/src”. Drag Three20.xcodeproj and drop it onto the root of your Xcode project’s “Groups and Files” sidebar. A dialog will appear — make sure “Copy items” is unchecked and “Reference Type” is “Relative to Project” before clicking “Add”.
  • Now you need to link the Three20 static library to your project. Click the “Three20.xcodeproj” item that has just been added to the sidebar. Under the “Details” table, you will see a single item: libThree20.a. Check the checkbox on the far right of libThree20.a.

  • Now you need to add Three20 as a dependency of your project, so Xcode compiles it whenever you compile your project. Expand the “Targets” section of the sidebar and double-click your application’s target. Under the “General” tab you will see a “Direct Dependencies” section. Click the “+” button, select “Three20”, and click “Add Target”.

  • Now you need to add the bundle of images and strings to your app. Locate “Three20.bundle” under “Three20/src” and drag and drop it into your project. A dialog will appear — make sure “Create Folder References” is selected, “Copy items” is unchecked, and “Reference Type” is “Relative to Project” before clicking “Add”.

  • Now you need to add the Core Animation framework to your project. Right click on the “Frameworks” group in your project (or equivalent) and select Add > Existing Frameworks. Then locate QuartzCore.framework and add it to the project.
  • Finally, we need to tell your project where to find the Three20 headers. Open your “Project Settings” and go to the “Build” tab. Be sure to select the appropriate active configuration (eg, Release vs. Debug — eventually you’ll need to change both). Look for “Header Search Paths” and double-click it. Add the relative path from your project’s directory to the “Three20/src” directory. If your project and the Three20 source are in the same parent, you would enter “../Three20/src”.
  • While you are in Project Settings, go to “Other Linker Flags” under the “Linker” section, and add “-ObjC” and “-all_load” to the list of flags.
  • You’re ready to go. Just #import “Three20/Three20.h” anywhere you want to use Three20 classes in your project.

!! Enjoy !!