UILabel NSTextAlignmentRight not working? - ios

I have problem with text right alignment . Actually in my DetailedViewController there is UILabel Called "lblnNewsTitle", For this Lable i am trying to set NSTextAlignmentRight but it doesn't work for me . can any one help me to solve this issue ?
Screenshot 1:
Screenshot 2 :
My Storyboard screenshot 3 :
Here is My Code :
- (void)viewDidLoad
{
[DetailTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[super viewDidLoad];
[self.lblDescription setNumberOfLines:0];
[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320, 765)];
self.txtViwNews.text=self.strDescription;
self.lblnNewsTitle.text=self.strTitle;
self.lblnNewsTitle.font=[UIFont fontWithName:#"GEEast-ExtraBold" size:14];
self.txtViwNews.font=[UIFont fontWithName:#"GE SS Unique" size:12];
self.lblnNewsTitle.textAlignment = NSTextAlignmentRight;
self.txtViwNews.textAlignment= NSTextAlignmentRight;
self.lblDateinDetail.text=self.strDate;
self.lblDateinDetail.font=[UIFont fontWithName:#"GEEast-ExtraBold" size:14];
self.lblDateinDetail.textColor=[UIColor blackColor];
[lblnNewsTitle setNumberOfLines:0];
[lblnNewsTitle sizeToFit];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strDetailImage]];
self.strImage.image = [UIImage imageWithData:data];
// Set border color and width of image
[_strImage.layer setBorderColor:[UIColor blackColor].CGColor];
[_strImage.layer setBorderWidth:1.0];
self.lblDescription.font=[UIFont fontWithName:#"GE SS Unique" size:kLblIntalFont];
self.lblDescription.textAlignment = NSTextAlignmentRight;
[self estimatedHeight:kLblIntalFont];
if (_strImage.image == nil)
{
[_strImage.layer setBorderColor:[UIColor blackColor].CGColor];
[_strImage.layer setBorderWidth:0];
[self.lblnNewsTitle setNumberOfLines:0];
self.lblnNewsTitle.frame = CGRectMake(self.lblnNewsTitle.frame.origin.x, self.lblnNewsTitle.frame.origin.y, self.lblnNewsTitle.frame.size.width, self.lblnNewsTitle.frame.size.height );
self.viwMidImage.frame=CGRectMake(self.viwMidImage.frame.origin.x, self.strImage.frame.origin.y, self.viwMidImage.frame.size.width, self.viwMidImage.frame.size.height);
[self.lblDescription setNumberOfLines:0];
[self.lblDescription sizeToFit];
self.lblDescription.frame = CGRectMake(self.lblDescription.frame.origin.x, self.viwMidImage.frame.origin.y+ self.viwMidImage.frame.size.height,self.lblDescription.frame.size.width,self.lblDescription.frame.size.height );
self.lblDescription.textAlignment = NSTextAlignmentRight;
}
else {
// if (!cell.imgNews ==nil)
self.lblnNewsTitle.frame = CGRectMake(self.lblnNewsTitle.frame.origin.x, self.lblnNewsTitle.frame.origin.y, self.lblnNewsTitle.frame.size.width, self.lblnNewsTitle.frame.size.height );
[self.lblDescription setNumberOfLines:0];
[self.lblDescription sizeToFit];
}
}

add NSTextAlignmentRight in directly in your Attribute Inspector at the same time remove [lblnNewsTitle sizeToFit]; and check
try this

From the Documentation:
- sizeToFit
Resizes and moves the receiver’s content view so it just encloses its
subviews.
You should invoke this method after:
Adding a subview (to the content view)
Altering the size or location of such a subview
Setting the margins around the content view
So, if you do sizeTofit under any alignment, the text will aligned to the left only. To fix this:
You can save the original label's width in a variable and set it after sizeToFit, or give it a fixed width to counter these problems:
If you still wish to use sizeToFit,Do something like this:
myLabel.textAlignment = NSTextAlignmentRight;
[myLabel setNumberOfLines:0];
[myLabel sizeToFit];
CGRect myFrame = myLabel.frame;
// Resize the frame's width to your requirement)
// width could also be myOriginalLabelFrame.size.width
myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, myWidth, myFrame.size.height);
myLabel.frame = myFrame;
you can find more useful info here

Related

how to make two UILabel side by side in iOS Programatically

I want to show two UILabel side by side programatically as show in the Image below.
As in the Image show the first Label is short value but it value is dyanmic and the second UILabel is more then two line as show in the Image. But the Second Label is set to Right side of the first UILabel.
Is there any way to do this in programatically way..
I try lot of thing to do this but nothing is help to me.
Any help be Appreciated.
try this:
UILabel *label1 = [[UILabel alloc]init];
[self.view addSubview:label1];
label1.backgroundColor = [UIColor greenColor];
label1.font = [UIFont systemFontOfSize:15];
label1.text = #"ABC";
// this is the way
[label1 setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
UILabel *label2 = [[UILabel alloc]init];
[self.view addSubview:label2];
label2.font = [UIFont systemFontOfSize:15];
label2.text = #"label2label2label2label2label2label2label2label2label2label2label2";
label2.backgroundColor = [UIColor orangeColor];
label2.numberOfLines = 0;
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(0);
make.top.mas_equalTo(400);
make.height.mas_equalTo(18);
}];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(label1.mas_right);
make.top.mas_equalTo(label1);
make.right.mas_offset(0);
}];

iOS sizeToFit not showing text

I'm creating these labels for a Storyboard view. I have autolayout set to OFF and I'm setting the numberoflines to 0 but the text is only displayed if I comment out sizeToFit. Then, of course, the text gets cut off when its height is greater than 40.
- (void)viewDidLoad
{
[super viewDidLoad];
first = #"This text fits in the label";
second = #"This large text is too large for the label but because the words are normal sized, shows the more button correctly at the bottom right";
third = #"Doesn't show the more button correctly because WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW";
firstlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 57, 295, 40)];
secondlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 152, 295, 40)];
thirdlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 225, 295, 40)];
[firstlbl setFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:14]];
[secondlbl setFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:14]];
[thirdlbl setFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:14]];
firstlbl.lineBreakMode = NSLineBreakByWordWrapping;
secondlbl.lineBreakMode = NSLineBreakByWordWrapping;
thirdlbl.lineBreakMode = NSLineBreakByWordWrapping;
firstlbl.numberOfLines = 0;
secondlbl.numberOfLines = 0;
thirdlbl.numberOfLines = 0;
[firstlbl sizeToFit];
[secondlbl sizeToFit];
[thirdlbl sizeToFit];
[firstlbl setText:first];
[secondlbl setText:second];
[thirdlbl setText:third];
[self.view addSubview:firstlbl];
[self.view addSubview:secondlbl];
[self.view addSubview:thirdlbl];
}
You're calling sizeToFit before you set the text, so it's sizing down to CGRectZero. Switch those calls and it'll work.
sizeToFit doesn't mean "automatically adjust your size to fit your content," it means "update your size right now to fit your content." Subsequent updates to the text won't change the frame.
If you want the former behavior, so that it automatically sizes itself to its content, autolayout is probably the easiest road to take.

How to adjust/set UIView size according to UILabel content

i used loop to create dynamic UIView. But i could not create UIView according the size of UILabel kindly help me as i could do further proceed.. need your help.. i will appreciate
for(NSString *item in myArray)
{
length = item.length;
self.custom=[[CustomView alloc]init];
self.custom.Label = [[UILabel alloc]initWithFrame:CGRectMake(40, yAxis, 100+item.length, 44)];
[self.custom setFrame:self.custom.Label.frame];
[self.custom sizeToFit];
yAxis=yAxis+50;
self.custom.tag=200+a;
a++;
[newViews addObject:self.custom];
length = item.length;
self.custom.Label = [[UILabel alloc]initWithFrame:CGRectMake(5,5,length+20,40)];
self.custom.button=[[UIButton alloc]initWithFrame:CGRectMake(85,10,12,10)];
[self.custom.Label setText:item];
// Tell the label to use an unlimited number of lines
[self.custom.Label setNumberOfLines:1];
[self.custom.Label sizeToFit];
self.custom.Label.textAlignment = UITextAlignmentCenter;
![this is image i have created uiview according the array values where uilabel more width than uiview so i need to set uiview according the uilabel][1]
UIImage *btnImage = [UIImage imageNamed:#"button_droparrow.png"];
[self.custom.button setImage:btnImage forState:UIControlStateNormal];
[self.custom.button addTarget:self
action:#selector(buttonPressed:)forControlEvents:UIControlEventTouchDown];
self.custom.button.tag=self.custom.button.tag+a;
self.custom.backgroundColor=[UIColor greenColor];
custom.Label.text=item;
custom.Label.backgroundColor = [UIColor yellowColor];
[self.custom addSubview:self.custom.button];
[self.custom addSubview:custom.Label];
// [self.custom addSubview:cv];
[self.view addSubview:self.custom];
}
You can get the size based of the UILabel content using the following code.
NSString * countString = aLbl.text;
CGSize s = [countString sizeWithFont:[UIFont fontWithName:#"Helvetica-Light" size:12] constrainedToSize:CGSizeMake(100, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
And alter the Size of any views using following code
CGRect rect = aView.frame;
rect.size.width = s.width;
rect.size.height = s.height;
aView.frame = rect;
try size to fit for label or view
[yourlabel sizeToFit];
or
[yourview sizeToFit];
Change setNumberOfLines:0 and run your app. I hope it helps you. And I request to you, if this is help you please vote me.
[self.custom.Label setNumberOfLines:0];
self.custom.Label.text = #"xyz.................";
[self.custom.Label sizeToFit];

Issue with vertical scrolling in UIScrollView

I am using following code to create my view.
self.percentage_ans_view = [[UIView alloc] init];
float height = 0.0f;
for (int i=0; i < answer_set.count; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20,height ,280,50 )];
[label setText: [self.answer_set objectAtIndex:i]];
[label setTextAlignment:NSTextAlignmentLeft];
[label setBackgroundColor:[UIColor clearColor]];
label.textColor = [UIColor colorWithRed:0.2941f green:0.4666f blue:0.9549f alpha:1.0f];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
[label sizeToFit];
// label.tag = 5000 + i;
label.userInteractionEnabled = YES;
label.font = [UIFont fontWithName:#"Arial" size:14.0f] ;
[self.percentage_ans_view addSubview:label];
height += label.frame.size.height;
NSLog(#"LABEL SIZE height : %f & width : %f",label.frame.size.height,label.frame.size.height);
NSLog(#"ans:%#", [self.answer_set objectAtIndex:i]);
UIButton *ans_btn = [UIButton buttonWithType:UIButtonTypeCustom];
ans_btn.frame = CGRectMake(0 - 5, height, (width * 3)+ 20,40 );//CGRectMake(0 - 5, 45 + (i * 80), (width * 3)+ 20,40 )
[ans_btn setTitle:[NSString stringWithFormat:#"%d%#",percent,#"% "] forState:UIControlStateNormal];
ans_btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
ans_btn.titleLabel.textColor = [UIColor whiteColor];
ans_btn.backgroundColor = [UIColor colorWithRed:0.2941f green:0.4666f blue:0.9549f alpha:1.0f] ;
// ans_btn.frame = frame; your desired size
ans_btn.clipsToBounds = YES;
height += ans_btn.frame.size.height;
[self.percentage_ans_view addSubview:ans_btn];
}
[self.swipe addSubview:self.percentage_ans_view];
Here self.swipe is UIScrollView which is not scrolling vertically. So i am not able to see last two labels and button of my view. What i am doing wrong ?
Set the contentSize property of your UIScrollView properly (basically the width/height of the content that can be displayed in the scroll view without scrolling), set the pagingEnabled property of the scroll view to YES, and then add your view that you want to scroll as a subview of the UIScrollView.
As long as the lenght of the subview is more than the width of the contentSize you specified, it should scroll vertically.
If this scrollView is an IBOutlet, check if the autolayout is disabled for the parent view.
If you are using auto layout, you should add constrains to the scrollViews subviews, that will fully specify it's contentSize.

Center vertically in UILabel with autoshrink

This is a little different from all the other "How do I center the text in a UILabel" questions here...
I have a UILabel with some text in it, I want to center the text vertically in the UILabel. What's the big deal, right? That's the default. The problem comes because my text is dynamic and I have autoshrink turn on. As the text grows larger, the font size shrinks. You get this behavior.
Notice that the font baseline has not moved, I want it to move so the numbers are centered vertically in the UILabel's frame.
Easy, right? I just remember the frame's original center in viewDidLoad
self.workoutTimeCenter = _workoutTimeLabel.center;
and then I call sizeToFit after I change the the text, right?
[_workoutTimeLabel sizeToFit];
_workoutTimeLabel.center = _workoutTimeCenter;
Well, sizeToFit did, I guess, exactly what it was supposed to do, resize the frame so the text fits without shrinking!
How can I vertically center the text in a UILabel while respecting baselines and autoshrink? (Note, an iOS5 and later solution is fine and I can even deal with an iOS6 and later solution.)
In my experience you can just set the -[UILabel baselineAdjustment] property to UIBaselineAdjustmentAlignCenters to achieve the effect you're describing.
From the docs:
baselineAdjustment
Controls how text baselines are adjusted when text
needs to shrink to fit in the label.
#property(nonatomic) UIBaselineAdjustment baselineAdjustment
Discussion
If the adjustsFontSizeToFitWidth property is set to YES,
this property controls the behavior of the text baselines in
situations where adjustment of the font size is required. The default
value of this property is UIBaselineAdjustmentAlignBaselines. This
property is effective only when the numberOfLines property is set to
1.
and
UIBaselineAdjustmentAlignCenters
Adjust text based relative to the center of its bounding box.
EDIT: adding a full view-controller that demonstrates this:
#interface TSViewController : UIViewController
#end
#implementation TSViewController
- (void) addLabelWithFrame: (CGRect) f baselineAdjustment: (UIBaselineAdjustment) bla
{
UILabel* label = [[UILabel alloc] initWithFrame: f];
label.baselineAdjustment = bla;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName: #"Courier" size: 200];
label.text = #"00";
label.textAlignment = NSTextAlignmentCenter;
label.backgroundColor = [UIColor lightGrayColor];
label.userInteractionEnabled = YES;
[self.view addSubview: label];
UIView* centerline = [[UIView alloc] initWithFrame: CGRectMake(f.origin.x, f.origin.y+(f.size.height/2.0), f.size.width, 1)];
centerline.backgroundColor = [UIColor redColor];
[self.view addSubview: centerline];
UITapGestureRecognizer* tgr = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(onTap:)];
[label addGestureRecognizer: tgr];
}
- (void) viewDidLoad
{
[super viewDidLoad];
[self addLabelWithFrame: CGRectMake(0, 0, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignCenters];
[self addLabelWithFrame: CGRectMake(0, 220, 320, 200)
baselineAdjustment: UIBaselineAdjustmentAlignBaselines];
}
- (void) onTap: (UITapGestureRecognizer*) tgr
{
UILabel* label = (UILabel*)tgr.view;
NSString* t = [label.text stringByAppendingString: #":00"];
label.text = t;
}
#end
when working in IB, be sure to set align baselines to center
Note: line break CANNOT be word wrap for this to work, so it will NOT work multiline (good to set the line break to Truncate tail)
-(void)fitVerticallyToLabel:(UILabel *)lbl
{
CGFloat fontSize = lbl.frame.size.width / lbl.text.length;
[lbl setFont:[UIFont fontWithName:#"Helvetica-Bold" size:fontSize]];
CGRect rect = lbl.frame;
rect.origin.y += rect.size.height - fontSize;
rect.size.height = fontSize;
[lbl setFrame:rect];
}
How to Use: Call this method after setting the text to your label.
label.text = #"text";
[self fitVerticallyToLabel:label];
Note: I ahev taken UILabel from xib. You can take it programmatically too in that case you will have to set its text alignment NSTextAlignMentCenter
Try to implement this logic:
-(void)adjustLabel1Text1:(NSString *)text1
{
UILabel *lbl_first = [UIFont fontWithName:#"Helvetica" size:12];
text1 = [text1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
float hedingLblHeight = [self calculateHeightOfTextFromWidth:text1 : [UIFont fontWithName:#"Helvetica" size:12] :118 :UILineBreakModeWordWrap];
lbl_first.text=text1;
[lbl_first setFrame:CGRectMake(lbl_first.frame.origin.x, lbl_first.frame.origin.y, 118, hedingLblHeight)];
lbl_first.lineBreakMode = UILineBreakModeWordWrap;
lbl_first.numberOfLines = 0;
[lbl_first sizeToFit];
//////////Adjust the lable or any UIControl below this label accordingly.
float endResultHeight=[self calculateHeightOfTextFromWidth:text2 : [UIFont fontWithName:#"Helvetica" size:15] :299 :UILineBreakModeWordWrap];
if(hedingLblHeight>secondImgTitleHeight)
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
else
{
[lbl_endResult setFrame:CGRectMake(lbl_endResult.frame.origin.x, lbl_first.frame.origin.y+lbl_first.frame.size.height+5, 299, endResultHeight)];
}
lbl_endResult.lineBreakMode=UILineBreakModeWordWrap;
lbl_endResult.numberOfLines = 0;
[lbl_endResult sizeToFit];
}
-(float) calculateHeightOfTextFromWidth:(NSString*)text : (UIFont*) withFont:(float)width :(UILineBreakMode)lineBreakMode
{
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
return suggestedSize.height;
}
It has helped me a lot.Hope it works for you.
Try
yourLabel.textAlignment = UITextAlignmentCenter;

Resources