How can you rotate text for UIButton and UILabel in Objective-C?
I wanted to provide an alternative response.
Instead of rotating the UILabel
, you can rotate the text within the label by deriving a subclass from UILabel
and overriding drawRect
. If you're using Interface Builder, you can specify this subclass instead of UILabel
in the Custom Class attribute of the Identity Inspector. This will allow you to build out your UI with XIBs, instead of programmatically creating the labels. The only caveat being that the text in Interface Builder will display horizontally. However, it will be rendered vertically in the app itself.
#import "RotatedLabel.h"
@implementation RotatedLabel
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextRotateCTM(context, -(M_PI/2));
UIFont* systemFont17 = [UIFont systemFontOfSize:17.0];
CGSize textSize = [self.text sizeWithFont:systemFont17];
CGFloat middle = (self.bounds.size.width - textSize.height) / 2;
[self.text drawAtPoint:CGPointMake(-self.bounds.size.height, middle) withFont:systemFont17];
CGContextRestoreGState(context);
}
@end
You do like this,
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 50, 70)];
label.numberOfLines = 2;
label.text = @"text";
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.highlightedTextColor = [UIColor blackColor];
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont systemFontOfSize:12];
//rotate label in 45 degrees
label.transform = CGAffineTransformMakeRotation( M_PI/4 );
[self addSubview:label];
[label release];
Try this:
lbl.transform= CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(270));
[*yourlabelname* setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
rotated image
pervious image