How to set the number of lines in uitextfield dynamically? - iphone

Actually i am trying to set the text in the textfield in next line when it becomes larger in the first line ad default. Can you please help me. my uitextfield is taken through the IB. and i am trying to write it and wants to post something like comment.
[viewFeedback setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"background_Feedback.png"]]];
CGSize size = [txtFeedback.text sizeWithFont:txtFeedback.font];
CGRect f = txtFeedback.frame;
f.size.height = ceil(size.width/f.size.width)*size.height;
txtFeedback.frame = f;
txtFeedback is the textfield name here..

Well this would be a Increasing the height of the UITextfield dynamically. Please follow this or add your custom frame
In your UITextViewDelegate implementation of textViewDidChange: you need to calculate the size of the text for the specific width and adjust accordingly.
-(void)textViewDidChange:(UITextView *)textView
{
NSString *text = [textView text];
NSFont *font = [textView font];
CGFloat width = [textView frame].size.width;
CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, 9999) lineBreakMode:UILineBreakModeWordWrap];
/* Adjust text view width with "size.height" */
}

Related

iPhone - Adjust UILabel width according to the text

How can I adjust the label Width according to the text? If text length is small I want the label width small...If text length is small I want the label width according to that text length. Is it possible?
Actually I have Two UIlabels. I need to place these two nearby. But if the first label's text is too small there will be a big gap. I want to remove this gap.
//use this for custom font
CGFloat width = [label.text sizeWithFont:[UIFont fontWithName:#"ChaparralPro-Bold" size:40 ]].width;
//use this for system font
CGFloat width = [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;
label.frame = CGRectMake(point.x, point.y, width,height);
//point.x, point.y -> origin for label;
//height -> your label height;
Function sizeWithFont: is deprecated in iOS 7.0, so you have to use sizeWithAttributes: for iOS 7.0+. Also to suport older versions, this code below can be used:
CGFloat width;
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
{
width = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:16.0 ]].width;
}
else
{
width = ceil([text sizeWithAttributes:#{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:16.0]}].width);
}
Using function ceil() on result of sizeWithAttributes: is recommended by Apple documentation:
"This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function."
sizeWithAttributes
// In swift 2.0
let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
lblDescription.numberOfLines = 0
lblDescription.text = "Sample text to show its whatever may be"
lblDescription.sizeToFit()
// Its automatically Adjust the height
Try these options,
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [#"Some string here" sizeWithFont:myFont];
// Get the width of a string when wrapping within a particular width
NSString *mystring = #"some strings some string some strings...";
CGSize size = [mystring sizeWithFont:myFont
forWidth:150.0
lineBreakMode:UILineBreakModeWordWrap];
You can also try with [label sizeToFit]; Using this method, you can set frame of two labels as,
[firstLabel sizeToFit];
[secondLabel sizeToFit];
secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);
sizeWithFont constrainedToSize:lineBreakMode: is the original method to use. Here is an example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
just use to if you using constrain in your view or xib or cell
[LBl sizeToFit];
if its not working then
dispatch_async(dispatch_get_main_queue(), ^{
[LBl sizeToFit];
});
Try the following:
/* Consider these two labels as the labels that you use,
and that these labels have been initialized */
UILabel* firstLabel;
UILabel* secondLabel;
CGSize labelSize = [firstLabel.text sizeWithFont:[UIFont systemFontOfSize:12]];
//change the font size, or font as per your requirements
CGRect firstLabelRect = firstLabel.frame;
firstLabelRect.size.width = labelSize.width;
//You will get the width as per the text in label
firstLabel.frame = firstLabelRect;
/* Now, let's change the frame for the second label */
CGRect secondLabelRect;
CGFloat x = firstLabelRect.origin.x;
CGFloat y = firstLabelRect.origin.y;
x = x + labelSize.width + 20; //There are some changes here.
secondLabelRect = secondLabel.frame;
secondLabelRect.origin.x = x;
secondLabelRect.origin.y = y;
secondLabel.frame = secondLabelRect;

set the width of a UIText view based on the content size property

TextView.contentSize.width does not work to set the UITextView's .frame.size.width.
[TextView setFrame:CGRectMake(TextView.frame.origin.x, TextView.frame.origin.y, TextView.contentSize.width, TextView.contentSize.height)];
Setting the UITextView's frame height to the contentSize.height property works to make the view's frame scale to the proper size for the current vertical size of the content. For some reason, the width of the view's frame does not respond in the same way. It just remains the same size regardless of the amount of text input.
When I log the contentsize of the UITextView dynamically, as I am typing in text to the view, the height property changes (at each line break), while the width does not. Makes me wonder what the width property is doing, what's it for.
Try this way..
UIFont *font = [UIFont fontWithName:#"Enriqueta" size:15];
NSString *text = #"Your text";
CGSize frameSize = [text sizeWithFont:font];
CGRect originalFrame = textViewA1.frame;
textViewA1.frame = CGRectMake(CGRectGetMinX(originalFrame), CGRectGetMinY(originalFrame), frameSize.width, frameSize.height);
As depending upon width of UITextView it should be like this:
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0]; //your font specification here
NSString *strText = yourTextView.text;
CGSize strsize = [strText sizeWithFont:myFont
forWidth:yourTextView.frame.size.width
lineBreakMode:UILineBreakModeWordWrap]; //get string size
yourTextView.frame = CGRectMake(yourTextView.frame.origin.x,yourTextView.frame.origin.y,strsize.width,strsize.height+10); //change accordingly

EDIT: UITextView Label is Cut in Half (Horizontally)

I need help with this peculiar problem. I have a multiple choice question app and I have the choices as UITextview. Sometimes, choice D gets cut in half for whatever reason.
Screenshot:
Not sure what's going on here. I basically have the UITextView frame adjust to its contentSize.
CGRect dFrame = choiceD.frame;
dFrame.size.height = choiceD.contentSize.height;
choiceD.frame = dFrame;
Any ideas? Thanks in advance.
Caculate the size of string:
NSString *choiceDString = #"Equal the present value....";
CGSize size = [choiceDString sizeWithFont:[UIFont systemFontOfSize:CHOICE_FONT_SIZE] constrainedToSize:CGSizeMake(CHOICE_WIDTH, 100000)];
Init a label to content the choice string:
UILabel *choiceDLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,size.width,size.height)];
choiceDLabel.text= choiceDString;
Add the subview label for button:
[button addSubview:choiceLabel];
Use this code..Yo have define height of label according to your text length...
NSString *summary;
summary = #" your text";
CGSize sizeofbuttonorlable = [summary sizeWithFont:[UIFont systemFontOfSize:30]
constrainedToSize:CGSizeMake(self.view.bounds.size.width - 40, MAXFLOAT)
lineBreakMode:UILineBreakModeWordWrap];
CGRect frame = CGRectMake(0.0f, 0.0f, 320.0f, sizeofbuttonorlable.height);
UILabel *choiceDLabel = [[UILabel alloc] initWithFrame:frame];
choiceDLabel.text= summary;
[button addSubview:choiceLabel];
Hope, this will help you...chill
My suggestion is to first Calculate the size of the text entered by you in the textView like:-
//Give the maximum size of label which that label can have.
CGSize maximumLabelSize = CGSizeMake(300,500);
CGSize expectedLabelSize = [Label.text sizeWithFont:Label.font constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];
//adjust the label the new height.
CGRect newDescFrame = Label.frame;
newLabelFrame.size.height = expectedLabelSize.height;
NSLog(#"%f",newLabelFrame.size.height);
//adjust the label the new width.
newLabelFrame.size.width = expectedLabelSize.width;
NSLog(#"%f",newLabelFrame.size.width);
//Set the label size according to the new height and width.
label.frame = newLabelFrame;
Write above mention code after entering the text in the textView.
Hope it helps.Thanks :)

Wrong calculation when computing size of NSString using sizeWithFont:constraintedToSIze:lineBreakMode

I have a UITableViewCell with a subview consisting of a UITextView. The content of the textview is dynamic, so I want to measure the exact width and height to create a cell and a textview with no need to scroll.
I have created the following method to measure the size the NSString will take up:
- (CGSize)getSizeOfString:(NSString *)str font:(NSString *)theFont fontSize:(CGFloat)theSize {
CGSize maxSize = CGSizeMake(280, CGFLOAT_MAX);
UIFont *font = [UIFont fontWithName:theFont size:theSize];
return [str sizeWithFont:font constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
}
I am using it in this way:
// CellForRowAtIndexPath
.....
CGSize size = [strTool getSizeOfString:text font:TEXT_FONT fontSize:TEXT_SIZE];
CGFloat width = size.width;
CGFloat height = size.height;
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 10, width, height)];
[textView setBackgroundColor:[UIColor blueColor]];
textView.font = [UIFont fontWithName:TEXT_FONT size:TEXT_SIZE];
textView.editable = NO;
// Set value
textView.text = text;
[cell.contentView addSubview:textView];
[textView release];
return cell;
// heightForRowAtIndexPath
NSString *returnStr;
if (indexPath.section == SECTION_SHORT)
returnStr = self.manchet;
else
returnStr = self.newsText;
return [strTool getSizeOfString:returnStr font:TEXT_FONT fontSize:TEXT_SIZE].height;
But no matter what the calculated height is too small, which results in a nasty scroll inside the cellView. It is worth mentioning that almost all texts contain linebreaks (\n).
What am I doing wrong here?
Thanks
I think your ** heightForRowAtIndexPath** should look something like this:
NSString *returnStr;
if (indexPath.section == SECTION_SHORT) returnStr = self.manchet;
else returnStr = self.newsText;
return [strTool getSizeOfString:returnStr font:TEXT_FONT
fontSize:TEXT_SIZE].height+10.0f*2.0f;
And also you should take into account what you made offset for text field 15px along X (which means what width for sizeWithFont should be smaller on 15px) and 10px from top, i suggest use same value for bottom to make it look centered.
contentView have margins too, take all this into account.
UITextView is need a little bigger space than the size you calculated. since it has a top margin and bottom margin, I'm not sure how much is that. If you want perfect fit, try
[NSString drawInRect:withFont:]
or just make a little more space for UITextView, you can find the extra space by trying.

How to adjust and make the width of a UILabel to fit the text size?

In my project, there is a UILabel with text. The font size is 16pt. The text contents are changed depending on different cases. I hope it can automatically adjust the width of UILabel to fit the total width of texts without stretching.
Is it possible?
This assumes you have already set the font:
label.text = #"some text";
[label sizeToFit];
You will also need to define a maximum width, and tell your program what to do if sizeToFit gives you a width greater than that maximum.
Here's how to do it, suppose the following messageLabel is the label you want to have the desired effect. Now, try these simple line of codes:
// Set width constraint for label; it's actually the width of your UILabel
CGFloat constrainedWidth = 240.0f;
// Calculate space for the specified string
CGSize sizeOfText = [yourText sizeWithFont:yourFont constrainedToSize:CGSizeMake(constrainedWidth, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,20,constrainedWidth,sizeOfText.height)];
messageLabel.text = yourText;
messageLabel.numberOfLines = 0;// This will make the label multiline
NSString *txt1=#"I am here.";
CGSize stringsize1 = [txt1 sizeWithFont:[UIFont systemFontOfSize:14]];
[label setFrame:CGRectMake(x,y,stringsize1.width,hieght)];
[label setText:txt1];
I see three options here.
First, make label's size big enough to hold any text. That's most simple, but does not always work well - depends on its surrounding views.
Second, Label can adapt size of the font for longer text (adjustsFontSizeToFitWidth property). This is often not desirable, different fonts in elements might look ugly.
Last option is to programmatically resize the label according to its currently holding text. To calculate the size required to hold the text with current font use something like this:
CGSize textSize = [[someLabel text] sizeWithFont:[someLabel font] forWidth:someLabel.bounds.size.width lineBreakMode:UILineBreakModeWordWrap];
If you set your font and its size already and if you have your frame defined, try using the following for these two common conditions:
if (label.text.length > maxCharPerLine) [label setNumberOfLines:0]; // infinite lines
else [label setNumberOfLines:1]; // one line only
// Adjust your font size to fit your desired width.
[label setAdjustsFontSizeToFitWidth:YES];
Using Auto Layout:
In the ViewController:
override func viewDidLoad() {
super.viewDidLoad()
sampleLabel.text = "Electrical Maintenance and Repair"
sampleLabel.sizeToFit()
}
As sizeWithFont is depreciated in IOS 7.0 then you below code
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
if (SYSTEM_VERSION_LESS_THAN(#"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [itemCat_text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:12]];
} else {
// code here for iOS 7.0
fontSize = [itemCat_text sizeWithAttributes:
#{NSFontAttributeName:
[UIFont fontWithName:#"Helvetica" size:12]}];
}
Follow this.
CGSize stringsize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]];
[label setFrame:CGRectMake(x,y,stringsize.width,height)];
[label setText: yourString];