Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use drawInRect:withAttributes: instead of drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment: in iOS 7

Tags:

ios

nsstring

ios7

This method is deprecated in iOS 7.0:

drawAtPoint:forWidth:withFont:fontSize:lineBreakMode:baselineAdjustment: 

Now use drawInRect:withAttributes: instead.

I can't find the attributeName of fontSize and baselineAdjustment.

Edit

Thanks @Puneet answer.

Actually, I mean if there doesn't have these key, how to implement this method in iOS 7?

Like below method:

+ (CGSize)drawWithString:(NSString *)string atPoint:(CGPoint)point forWidth:(CGFloat)width withFont:(UIFont *)font fontSize:(CGFloat)fontSize            lineBreakMode:(IBLLineBreakMode)lineBreakMode       baselineAdjustment:(UIBaselineAdjustment)baselineAdjustment {     if (iOS7) {         CGRect rect = CGRectMake(point.x, point.y, width, CGFLOAT_MAX);          NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];         paragraphStyle.lineBreakMode = lineBreakMode;          NSDictionary *attributes = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle};          [string drawInRect:rect withAttributes:attributes];          size = CGSizeZero;     }     else {         size = [string drawAtPoint:point forWidth:width withFont:font fontSize:fontSize lineBreakMode:lineBreakMode baselineAdjustment:baselineAdjustment];     }     return size; } 

I don't know how to pass fontSize and baselineAdjustment to

attributes dictionary.

e.g.

NSBaselineOffsetAttributeName key should pass a NSNumer to it, but the baselineAdjustment is Enum.

Isn't there have other way to pass the two variables?

like image 226
Vincent Sit Avatar asked Oct 18 '13 06:10

Vincent Sit


1 Answers

You can use NSDictionary and apply attributes like this:

NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:14.0];  NSDictionary *attrsDictionary =  [NSDictionary dictionaryWithObjectsAndKeys:                               font, NSFontAttributeName,                               [NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil]; 

Use attrsDictionary as argument.

Refer: Attributed String Programming Guide

Refer: Standard Attributes

SWIFT: IN String drawInRect is not available but we can use NSString instead:

let font = UIFont(name: "Palatino-Roman", size: 14.0) let baselineAdjust = 1.0 let attrsDictionary =  [NSFontAttributeName:font, NSBaselineOffsetAttributeName:baselineAdjust] as [NSObject : AnyObject] let str:NSString = "Hello World" str.drawInRect(CGRectZero, withAttributes: attrsDictionary) 
like image 95
Puneet Sharma Avatar answered Sep 30 '22 02:09

Puneet Sharma