Issue with vertical scrolling in UIScrollView - ios

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.

Related

UIFont for Label not cooperating with size settings

I want to make a game title but I can't seem to make the font larger. Here's what I have. I opted to not use CGRectMake initializer setting because I wanted to just set the x and y positions, not the size of the label (which I presumed would've been dictated by the size: portion of the UIFont method below). The 100.0 is no different from size 40.0.
UILabel *title = [[UILabel alloc] init];
CGRect frame = title.frame;
frame.origin.y = 30;
frame.origin.x = 100;
title.frame= frame;
title.text = #"TWINSTONES";
title.backgroundColor = [UIColor clearColor];
title.font = [UIFont fontWithName:#"TWINSTONES" size:100.0];
[title setTextColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
title.numberOfLines = 0;
[title sizeToFit];
[self.view addSubview:title];

UILabel NSTextAlignmentRight not working?

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

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;

UILabel number of lines affecting the bounds size

I am having this peculiar behavior with UILabel. Any numberOfLines works ok, except 1. If I set the number of lines to 1 it ignores the width which I set later.
I don't understand why 1 line screws it up...
here is my code
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
CGRect rect = label.frame;
label.numberOfLines = 2;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
rect.size.width = 100;
label.frame = rect;
[label sizeToFit];
Use this code:
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 3;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
With numberOfLines = 3:
With numberOfLines = 1:
If you wanna use numberOfLines = 1 in that case your text will be in one line.So please use numberOfLines = 0;
label.numberOfLines = 0;
And there is no need to again define label frame so please remove these statement.
CGRect rect = label.frame;
rect.size.width = 100;
label.frame = rect;
Use this code this is perfect..
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.frame = CGRectMake(20, 20, 100, 0);
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
[label sizeToFit];
Yes, it doesn't work when numberOfLines=1
I have to add this line at the end to make it work for all cases..
label.width = min(label.width, 100)
Use this as :
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor greenColor];
label.text = #"here is my label with lots of text to fill, here is my label with lots of text to fill";
label.numberOfLines = 0;
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(100 , 9999) lineBreakMode:label.lineBreakMode];
float lHeight = labelSize.height;
label.frame = CGRectMake(20, 20, 100, lHeight);
label.lineBreakMode = NSLineBreakByTruncatingTail;
[self.view addSubview:label];
EDIT : - (void)sizeToFit
Description :
Resizes and moves the receiver view so it just encloses its subviews.
Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds. Thus, if you want a given view to size itself to its parent view, you should add it to the parent view before calling this method.
// [label sizeToFit];
Hope it helps you.

Graphical Bugs while programmatically creating UILabel, UITextField, etc

I programmatically created a login view and a table view.
Under certain circumstances which i cannot reproduce there occur some strange visual bugs:
Text with some letters having a different font size than others
A button where the border is not initially shown but only if you click on it. In the same case, the border of the button can be shown in a UITextField instead of the place holder ( see screenshot )
A label showing up not in the right place, but in the above mentioned textfield, upside down ( i did not manage to screenshot this one yet )
Below, i added two screenshots with most of the app blacked out, only showing the bugs:
http://uppix.net/b/c/4/dd1e41acb94b7d0ad8eb173772e97.png
http://uppix.net/b/f/2/a5993440c07753b851701068330be.png
Here you can see that text gets mixed with different font sizes.
This errors occur not regularly or reproduce-able.
I added the code of the login screen below:
// Implement loadView to create a view hierarchy programmatically, without
// using a nib.
- (void)loadView {
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
UIFont* font = [UIFont systemFontOfSize:14];
float midLine = 100.0;
float height = 30.0;
float borderY = 70.0;
float borderX = 10.0;
float width = 320.0 - borderX * 2.0;
float paddingX = 10.0;
float paddingY = 5.0;
CGRect usernameLabelRect = CGRectMake(borderX, borderY, midLine, height);
CGRect usernameFieldRect = CGRectMake(borderX + midLine + paddingX, borderY,
width - midLine - paddingX - 40 , height);
CGRect passwordLabelRect = CGRectMake(borderX, borderY + height + paddingY,
midLine, height);
CGRect passwordFieldRect = CGRectMake(borderX + midLine + paddingX,
borderY + height + paddingY,
width - midLine - paddingX - 40, height);
CGRect loginButtonRect = CGRectMake(borderX + 40,
borderY + height*2 + paddingY*2, width - 80,
height);
//CGRect warningRect = CGRectMake(borderX,
// borderY * height * 3.0 + paddingY *3.0,
// width, height);
CGRect warningRect = CGRectMake(borderX, 175, width, 40);
UILabel* usernameLabel = [[UILabel alloc] initWithFrame:usernameLabelRect];
usernameLabel.textAlignment = UITextAlignmentRight;
usernameLabel.font = font;
usernameLabel.text = #"Username:";
UILabel* passwordLabel = [[UILabel alloc] initWithFrame:passwordLabelRect];
passwordLabel.textAlignment = UITextAlignmentRight;
passwordLabel.font = font;
passwordLabel.text = #"Password:";
usernameField = [[UITextField alloc] initWithFrame:usernameFieldRect];
[usernameField setBorderStyle:UITextBorderStyleRoundedRect];
//[usernameField setPlaceholder:#"<Username>"];
usernameField.font = font;
usernameField.autocapitalizationType = UITextAutocapitalizationTypeNone;
usernameField.autocorrectionType = UITextAutocorrectionTypeNo;
passwordField = [[UITextField alloc] initWithFrame:passwordFieldRect];
passwordField.font = font;
[passwordField setBorderStyle:UITextBorderStyleRoundedRect];
//[passwordField setPlaceholder:#"<Password>"];
passwordField.autocapitalizationType = UITextAutocapitalizationTypeNone;
passwordField.autocorrectionType = UITextAutocorrectionTypeNo;
passwordField.secureTextEntry = YES;
loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
loginButton.frame = loginButtonRect;
[loginButton setTitle: #"Einloggen" forState:UIControlStateNormal];
[loginButton setTitleColor:[UIColor blackColor]
forState:UIControlEventTouchDown];
loginButton.contentVerticalAlignment =
UIControlContentVerticalAlignmentCenter;
loginButton.contentHorizontalAlignment =
UIControlContentHorizontalAlignmentCenter;
[loginButton addTarget:self action:#selector(OnLoginClicked:)
forControlEvents:UIControlEventTouchUpInside];
[loginButton setBackgroundColor:[UIColor clearColor]];
warningLabel = [[UILabel alloc] initWithFrame:warningRect];
warningLabel.font = font;
warningLabel.numberOfLines = 3;
warningLabel.text =
#"Wenn Sie die Applikation jetzt schließen, so werden Ihre Logindaten verworfen.";
[myView addSubview:usernameLabel];
[myView addSubview:passwordLabel];
[myView addSubview:usernameField];
[myView addSubview:passwordField];
[myView addSubview:loginButton];
[myView addSubview:warningLabel];
/*
[usernameLabel release];
[passwordLabel release];
[usernameField release];
[passwordField release];
[loginButton release];
[warningLabel release];
*/
self.view = myView;
[myView release];
}
I can't work all of your screen positioning in my head, but it looks to me like many of your fields overlap : is this intentional ? Maybe that is the cause ? I normally create views in code, but this might be one case for IB!
You haven't shown any code for the table view, however I've seem similar issues before where you add subviews to a cell, then next time the cell is deQueued with DequeueReusableCell you add subviews again without checking if they are there or clearing them. This results in all sorts of overlaps just like the first screenshot.
The problem was that i called UIKit messages from Not-The-Main-Thread, which causes all kinds of graphical problems. Solved it by using performSelectorOnMainThread: in several places in my code =)

Resources