Vertically align text in a UILabel - iphone

I am new to iPhone,
How do I vertically align my text in the UILabel?
Here is my Code snippet,
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,100,100);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
[scrollVw addSubview:lbl];
text displayed is in the format of 123456 but i want text should be display vertically like,
6
5
4
3
2
1
Any help will be appriciated.

Its impossible to align the text in UILabel vertically. But, you can dynamically change the height of the label using sizeWithFont: method of NSString, and just set its x and y as you want.
As an alternative you can use UITextField. It supports the contentVerticalAlignment peoperty as it is a subclass of UIControl. You have to set its userInteractionEnabled to NO to prevent user from typing text on it.
EDIT 1
Well instead of a UILabel , Make a UITableView like :-
TableActivityLevel=[[UITableView alloc] initWithFrame:CGRectMake(224, 203, 27, 0) style:UITableViewStylePlain];
TableActivityLevel.delegate=self;
TableActivityLevel.dataSource=self;
TableActivityLevel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
TableActivityLevel.rowHeight = 17;
TableActivityLevel.backgroundColor=[UIColor clearColor];
TableActivityLevel.layer.borderColor = [[UIColor clearColor]CGColor];
TableActivityLevel.separatorStyle = UITableViewCellSeparatorStyleNone;
EDIT 2 Found the method using UILabels too !! :) Check this out....
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 10.0, 100.0)];
[label1 setBackgroundColor:[UIColor clearColor]];
[label1 setNumberOfLines:0];
[label1 setCenter:self.view.center];
[label1 setFont:[UIFont fontWithName:#"Helvetica" size:12.0]];
[label1 setTextColor:[UIColor whiteColor]];
[label1 setTextAlignment:UITextAlignmentCenter];
[label1 setText:#"1 2 3 4 5 6"];
[self.view addSubview:label1];

If it just a single lined text as in your example you can use various workarounds. I personally would create a UILabel subclass as follows,
#implementation VerticalLabel
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.numberOfLines = 0;
}
return self;
}
- (void)setText:(NSString *)text {
NSMutableString *newString = [NSMutableString string];
for (int i = text.length-1; i >= 0; i--) {
[newString appendFormat:#"%c\n", [text characterAtIndex:i]];
}
super.text = newString;
}
#end
You now just have to replace
UILabel *lbl = [[UILabel alloc] init];
with
UILabel *lbl = [[VerticalLabel alloc] init];
to get vertical text.

Hi the following code is work well
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,10,300);
lbl.backgroundColor=[UIColor clearColor];
lbl.numberOfLines=6; // Use one to 6 numbers
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
NSString *reverse=lbl.text;
NSMutableString *reversedString = [NSMutableString string];
NSInteger charIndex = [reverse length];
while (charIndex > 0) {
charIndex--;
NSRange subStrRange = NSMakeRange(charIndex, 1);
[reversedString appendString:[reverse substringWithRange:subStrRange]];
}
NSLog(#"%#", reversedString);
CGSize labelSize = [lbl.text sizeWithFont:lbl.font
constrainedToSize:lbl.frame.size
lineBreakMode:lbl.lineBreakMode];
lbl.frame = CGRectMake(
lbl.frame.origin.x, lbl.frame.origin.y,
lbl.frame.size.width, labelSize.height);
lbl.text=reversedString;
[scrollview addSubview:lbl];

UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,10,100);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"123456";
lbl.numberOfLines = 10;
[self.view addSubview:lbl];

You cant do vertical allignment but use another way to display it
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(10,10,100,400);
lbl.backgroundColor=[UIColor clearColor];
lbl.font=[UIFont systemFontOfSize:13];
lbl.text=#"1\n2\n3\n4\n5\n6";
[scrollVw addSubview:lbl];

Related

How can set right margin in UItextfield and also placeholder text?

I tried to set the right side margin in UItextfield but I can't get success for this.
I tried below code:
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(1, 1, 60, 25) ];
[lbl setText:#"Partenza:"];
[lbl setFont:[UIFont fontWithName:#"Verdana" size:12]];
[lbl setTextColor:[UIColor grayColor]];
[lbl setTextAlignment:UITextAlignmentLeft];
txtFCarat.rightView = lbl;
txtFCarat.rightViewMode = UITextFieldViewModeAlways;
txtFCarat.delegate = self;
Please help me if any body have a solution for this!
You can override this below two methods
#implementation rightTextField
// placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectInset( self.bounds , margin position , margin position );
}
// text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectInset( self.bounds , margin position ,margin position );
}
Edit: use to bind code like
textField.bounds = [self editingRectForBounds:textField.bounds];
textField.bounds = [self textRectForBounds:textField.bounds];
Your expected Answer:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon.png"]];
textfield.rightView = imageView;
textfield.rightViewMode = UITextFieldViewModeAlways;
Add the below line where you are creating textfield..and set value as per requirement
textField.layer.sublayerTransform = CATransform3DMakeTranslation(-20, 000, 0);
Another way to achieve this by overriding the textRectForBounds
Let me to give complete Description how to do this or achieve it
First you create a class and name "textField"(or what ever you Want) and must be sure that IT IS SUBCLASS OF UITextField.
2.Now open the textfield.m class and use this code or paste below code in this class (textfield):
- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 50, bounds.origin.y,
bounds.size.width - 20, bounds.size.height);
}
-(CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
If you want to customize the textfield more then you can use here only or in calling Class like
use the below code :Note it is only for testing purpose.it depend on your requirement
- (void)settingTextField {
[self setTextField];
[self setKeyboardAppearance:UIKeyboardAppearanceAlert];
}
- (void)setTextField {
[self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
[self setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[self setTextAlignment:NSTextAlignmentCenter];
[self setValue:[UIColor colorWithRed:120.0/225.0 green:120.0/225.0 blue:120.0/225.0 alpha:1.0] forKeyPath:#"_placeholderLabel.textColor"];
[self setFont:[UIFont boldSystemFontOfSize:15.0f]];
}
3.improt textField.h class into your view-controller where you wants to create textfield
and you call it like this.
#import "textField.h"
//Viewcontroller Class
- (void)viewDidLoad
{
[super viewDidLoad];
textField *field1 = [[textField alloc] initWithFrame:CGRectMake(50, 50, 200, 20)];
field1.backgroundColor=[UIColor greenColor];
field1.placeholder=#"0";
[self.view addSubview:field1];
}
Try to adjust the value textRectForBounds as per you reqitement
NSString *myString = #"Partenza:";
UIFont *myFont = [UIFont fontWithName:#"Verdana" size:12];
CGSize myStringSize = [myString sizeWithFont:myFont];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, myStringSize.width + 10, 25) ];
[lbl setText:myString];
[lbl setFont:[UIFont fontWithName:#"Verdana" size:12]];
[lbl setTextColor:[UIColor grayColor]];
[lbl setTextAlignment:UITextAlignmentLeft];
txtFCarat.rightView = lbl;
txtFCarat.rightViewMode = UITextFieldViewModeAlways;

How to set UIlabel TextColor Dynamically

I have created more than one label using this code,
.H file
#interface ViewController : UIViewController
{
NSArray * phraseAry ;
UIView * containerView;
UILabel * oldLabel;
NSMutableArray *dataArray;
}
#property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
.M file
- (void)viewDidLoad
{
[super viewDidLoad];
heightValue = 20;
widthValue = 0;
xValue = 5;
yValue = 10;
containerView = [[UIView alloc] init];
for (int i=0; i<phraseAry.count; i++) {
widthValue = [self returnWidth:[phraseAry objectAtIndex:i]];
int newXValue = xValue+widthValue+5;
//NSLog(#"newXValue : %i",newXValue);
if (newXValue > 310) {
yValue +=20;
xValue = 5;
newXValue = xValue+widthValue+5;
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:#"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
} else {
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(xValue, yValue, widthValue, heightValue)];
lbl.text = [phraseAry objectAtIndex:i];
[lbl setFont:[UIFont fontWithName:#"Helvetica" size:14.0]];
lbl.tag = i;
lbl.textColor = [UIColor colorWithRed:(92/255.0) green:(109/255.0) blue:(43/255.0) alpha:1];
[containerView addSubview:lbl];
xValue = newXValue;
}
}
containerView.frame = CGRectMake(0, 0, 320, yValue);
//add code to customize, e.g. polygonView.backgroundColor = [UIColor blackColor];
[self.myScrollView addSubview:containerView];
self.myScrollView.contentSize = containerView.frame.size;
}
And than i set background color and textcolor in specific table using this code
- (void)updateLabelMethod
{
oldLabel.backgroundColor = [UIColor clearColor];
UILabel *label = (UILabel *)[containerView viewWithTag:2];
oldLabel = label;
label.backgroundColor = [UIColor colorWithRed:(98/255.0) green:(147/255.0) blue:(216/255.0) alpha:1];
label.textColor = [UIColor whiteColor];
containerView.backgroundColor = [UIColor clearColor];
}
It will update background of label fine but when i use this code to update textcolor it will display error like this
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setTextColor:]: unrecognized selector sent to instance 0xbaa3b30'
Any ways to set textcolor? Plz help.
Start your label tag from 1 instead of 0, because by default the tag value is 0 for all view.
lbl.tag = i+1;
Because
UILabel *label = (UILabel *)[containerView viewWithTag:0];
it will return containerView itself, and UIView not have textColor property :P
[containerView viewWithTag:2];
check container view has only one view that is a label with tag 2.
May be some other view is set with tag 2 and may be causing the issue.
NSLog(#"%#",label);
can give you what the label here gives the output .It should point out an UILabel itself
make use of isKindOfClass: to identify it is a label you are updating
for (UILable *lblTemp in containerView.subviews){
if ([lblTemp isKindOfClass:[UILable class]] && lblTemp.tag==2){
// change the lbl color
break;
}
}
check using this code ;)

How to add padding-left on a UILabel created programmatically?

I know this is a noob question but ...I have these labels on a tableview, but the text is completely squished to the left. I want to add a bit of padding. How do I go about it?
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10,0,300,60)] autorelease];
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
headerLabel.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:#"color"]];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.frame = CGRectMake(0,0,400,30);
headerLabel.text = [[_months objectAtIndex:section] objectForKey:#"name"];
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
any help is much appreciated! Thanks!
For a full list of available solutions, see this answer: UILabel text margin
The most flexible approach to add padding to UILabel is to subclass UILabel and add an edgeInsets property. You then set the desired insets and the label will be drawn accordingly.
OSLabel.h
#import <UIKit/UIKit.h>
#interface OSLabel : UILabel
#property (nonatomic, assign) UIEdgeInsets edgeInsets;
#end
OSLabel.m
#import "OSLabel.h"
#implementation OSLabel
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.edgeInsets)];
}
#end
you can simple add white space at the begin of you text;
[NSString stringWithFormat:#" %#",text];
It is 'evil' way to add 'padding', but it may help.
I found a better way to do this:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = CGRectMake(0, 0, 320, 25);
UIView *customView = [[UIView alloc] initWithFrame:frame];
UILabel *sectionTitle = [[UILabel alloc] init];
[customView addSubview:sectionTitle];
customView.backgroundColor = [UIColor redColor];
frame.origin.x = 10; //move the frame over..this adds the padding!
frame.size.width = self.view.bounds.size.width - frame.origin.x;
sectionTitle.frame = frame;
sectionTitle.text = #"text";
sectionTitle.font = [UIFont boldSystemFontOfSize:17];
sectionTitle.backgroundColor = [UIColor clearColor];
sectionTitle.textColor = [UIColor whiteColor];
[sectionTitle release];
tableView.allowsSelection = NO;
return [customView autorelease];
}
Set the backgroundColor on the customView also
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = tableView.bounds;
frame.size.height = HEADER_HEIGHT;
UIView* customView = [[[UIView alloc] initWithFrame:frame] autorelease];
customView.backgroundColor = [UIColor redColor];
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] autorelease];
// Orientation support
headerLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
headerLabel.backgroundColor = [UIColor redColor];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.text = #"My Text Label";
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
Try not to hardcode magic numbers: (add these to top of file)
#define HEADER_HEIGHT 60.0f
#define LABEL_PADDING 10.0f
Should give this
Try the following & play around with the padding etc.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGFloat headerHeight = 60, padding = 10;
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,headerHeight)] autorelease];
customView.backgroundColor = [UIColor colorWithHexString:[[_months objectAtIndex:section] objectForKey:#"color"]];
CGRect frame = CGRectMake(padding,padding,320 - 2*padding,headerHeight-2*padding);
UILabel *headerLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
headerLabel.font = [UIFont boldSystemFontOfSize:18];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.text = [[_months objectAtIndex:section] objectForKey:#"name"];
headerLabel.textColor = [UIColor whiteColor];
[customView addSubview:headerLabel];
return customView;
}
You can create a subclass of UILabel and override intrinsicContentSize and - (CGSize)sizeThatFits:(CGSize)size:
- (CGSize) intrinsicContentSize
{
CGSize parentSize = [super intrinsicContentSize];
parentSize.width += 2*PADDING_VALUE;
return parentSize;
}
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize parentSize = [super sizeThatFits:size];
parentSize.width += 2*PADDING_VALUE;
return parentSize;
}
True, it's a bit inexact and hackish, but you could always add a space in front of the month name like this:
headerLabel.text = [NSString stringWithFormat:#" %#",
[[_months objectAtIndex:section] objectForKey:#"name"]];
You could use a UITextView instead. I did this in Cocoa but I'm pretty sure it translates to UITextView:
NSTextView *headerLabel = [[[NSTextView alloc] initWithFrame:NSMakeRect(20.0, 20.0, 400.0, 20.0)] autorelease];
[headerLabel setBackgroundColor: [NSColor redColor]];
[headerLabel setString: #"Testing Stuff"];
[headerLabel setTextColor: [NSColor whiteColor]];
NSSize txtPadding;
txtPadding.width = 20.0;
txtPadding.height = 0.0;
[headerLabel setTextContainerInset:txtPadding];
[[mainWin contentView] addSubview:headerLabel];

iPhone dynamic addition of UILabel overlap

I am parsing the XML file through URL and displaying the values as label dynamically.
If values are changed in xml file, the new values of labels are overlapped on old values
How should i fix it
In viewDidLoad
for(int i=0;i<[appDelegate.books count]; i++){
[self createLabel:labelname labelFrame:CGRectMake(LXCOOR, LYCOOR,LWIDTH,LHEIGHT)];
}
-(void) createLabel :(NSString * ) aTitle labelFrame:(CGRect) aFrame{
label1 =[[UILabel alloc] initWithFrame:aFrame];
//label.font=[UIFont fontWithName:#"Helvetica" size:TEXTSIZE];
label1.font=[UIFont systemFontOfSize: 10];
label1.textAlignment = UITextAlignmentLeft;
label1.text=[NSString stringWithString:aTitle];
label1.textColor=[UIColor blackColor];
label1.backgroundColor = [UIColor clearColor];
[sv addSubview:label1];
[self.view addSubview:sv];
}
remove the sv before adding it to the view...
-(void) createLabel :(NSString * ) aTitle labelFrame:(CGRect) aFrame{
if ([[sv subviews] count] > 0)
{
for(int i=0 ; i< [[sv subviews] count] ; i++)
{
UIView *subView = [[sv subviews] objectAtIndex:0];
[subView removeFromSuperview];
i++;
}
}
[sv removeFromSuperView];
label1 =[[UILabel alloc] initWithFrame:aFrame];
//label.font=[UIFont fontWithName:#"Helvetica" size:TEXTSIZE];
label1.font=[UIFont systemFontOfSize: 10];
label1.textAlignment = UITextAlignmentLeft;
label1.text=[NSString stringWithString:aTitle];
label1.textColor=[UIColor blackColor];
label1.backgroundColor = [UIColor clearColor];
[sv addSubview:label1];
[self.view addSubview:sv];
}
In viewDidLoad add,
[self.view addSubview:sv];
Then modify the "createLabel" function to
-(void) createLabel :(NSString * ) aTitle labelFrame:(CGRect) aFrame{
for(UIView *tempView in [sv subviews]) {
[subView removeFromSuperview];
}
label1 =[[UILabel alloc] initWithFrame:aFrame];
//label.font=[UIFont fontWithName:#"Helvetica" size:TEXTSIZE];
label1.font=[UIFont systemFontOfSize: 10];
label1.textAlignment = UITextAlignmentLeft;
label1.text=[NSString stringWithString:aTitle];
label1.textColor=[UIColor blackColor];
label1.backgroundColor = [UIColor clearColor];
[sv addSubview:label1];
}
as mentioned above, you shouldn't recreate the label over and over. Instead you should create one instance of it in viewDidLoad (or something that loads once)
-(void)viewDidLoad { ...
//code
CGRect aFrame = CGRectMake(x, y, width, height);
label1 =[[UILabel alloc] initWithFrame:aFrame];
[sv addSubview:label1];
[self.view addSubview:sv];
}
next you should call createLabel where you want to, for instance a button click or a scroll gesture. This should be your new createLabel without adding a subview
-(void) createLabel :(NSString * ) aTitle labelFrame:(CGRect) aFrame{
label1.font=[UIFont systemFontOfSize: 10];
label1.textAlignment = UITextAlignmentLeft;
label1.text=[NSString stringWithString:aTitle];
label1.textColor=[UIColor blackColor];
label1.backgroundColor = [UIColor clearColor];
}

UIView with adaptable height according to content - Objective-c

I would like to create an UIView that fits his content. The content is an UILabel with dinamic text.
UIView *myview = [ [UIView alloc ] initWithFrame:CGRectMake(10.0, 10.0, 700.0, 100.0)];
myview.backgroundColor = [UIColor redColor];
[self.view addSubview:myview];
UILabel *myLabel = [ [UILabel alloc ] initWithFrame:CGRectMake(10.0, 10.0, 500.0, 43.0) ];
myLabel.textAlignment = UITextAlignmentLeft;
myLabel.textColor = [UIColor whiteColor];
myLabel.backgroundColor = [UIColor blackColor];
myLabel.font = [UIFont fontWithName:#"Arial Rounded MT Bold" size:(36.0)];
[myView addSubview:myLabel];
myLabel.numberOfLines = 0;
myLabel.text = #"This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. ";
[myLabel sizeToFit];
I attach a screenshot:
Screenshot
Try this after [myLabel sizeToFit]:
[myView setFrame:myLabel.frame];
This will do the trick:
NSString *tempString = #"This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. This is an UILabel. ";
CGSize constSize = { 260.0f, 20000.0f };
CGSize textSizeTitle = [tempString sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constSize lineBreakMode:UILineBreakModeWordWrap];
UILabel *EventTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 260,textSizeTitle.height)];
[EventTitle setText:tempString];
[EventTitle setBackgroundColor:[UIColor clearColor]];
[EventTitle setFont:[UIFont fontWithName:#"TrebuchetMS-Bold" size:20]];
[EventTitle setNumberOfLines:0];
[EventTitle setUserInteractionEnabled:NO];
[EventTitle setTextColor:[UIColor whiteColor]];
[newsBox addSubview:EventTitle];
Just ensure, font size of textSizeTitle & EventTitle should be same.