Finding the number of lines in UITextView - iphone

I'm using UIScrollView in which I have placed a UIImageView and a UITextView. I make the UIScrollView to scroll both the images and text and it works fine, but my UITextView contains dynamic text (i.e number of lines is different for each time). So I can't find the way to assign contentSize of UITextView. Is there any way to do this?

This and this might help you.
You can put a condition that if width of the new CGSize is greater than textview width then number of lines = 2 else 1.

calculate the text width and define your text view width using below code
+(float) calculateHeightOfTextFromWidth:(NSString *) text: (UIFont *)withFont: (float)width
:(UILineBreakMode)lineBreakMode
{
[text retain];
[withFont retain];
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(215, 1000) lineBreakMode:lineBreakMode];
[text release];
[withFont release];
return suggestedSize.height;
}
and use when you want to display dynamic text as
float titleHeight;
titleHeight = [Your view controllre ViewController calculateHeightOfTextFromWidth:[NSString stringWithFormat:#"%#",[dict objectForKey:#"title"]] :[UIFont systemFontOfSize:14]:300 :UILineBreakModeTailTruncation];
give this titleHeight to your textview or do calculation dividation using titleheight ,you can get the number of lines
If you get problem then reply

Related

how to make UILabel dynamically without overlapping with other UILabel

I've tried to search online, but haven't found a clear answer for my issue so I've come to ask for your expert advice. I have a view with 2 labels on it. Both label will display different string length from the plist.
When i run the app, the label will overlapped with other label depending on the string length.
Below is the screenshot for my problem
You have to change your secondLabel origin.
CGRect frame = secondLabel.frame;
frame.origin.y= firstLabel.frame.origin.y + firstLabel.frame.size.height;
[secondLabel setFrame:frame];
Better option is to use UITextView instead of UILabel but if you still want to go with lable then
with the use of below code you can find the height of the text and can set your lable's frame according to that height
NSString *text = [arr objectAtIndex:indexPath.row];
CGSize constraint = CGSizeMake(contentWidth - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:20] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height, 44.0f);
here contentWidth is the width of your label and CELL_CONTENT_MARGIN = 10;
You need to set the 'Y' of second label. Take the Height of first label text and then set it to the Second Label 'Y'.
Hope it'll help you.
CGSize LblSize=[[Label1 text] sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(320.0f, 400.0f)];
UILabel *Label2=[[UILabel alloc] initWithFrame:Label2Rect];
CGRect Label2Rect=[Label2 Frame];
Label2Rect.origin.y=LblSize.height+30.0f; //add some extra spaces, I have added 30.0f here
[Label2 setFrame:Label2Rect];
Ey, you can solve it in many ways.
For example, you can fill your first label with the dessired text and then call to
[label1 sizeToFit]
With that call, your label now has the proper size, adapted to the lenght of your text. Now you can just place your second label after your first one.
label2.frame = CGRectMake (x, label1.frame.size.height + ..., .....)
Hope it helps!

Initializing UITextView based on the available text font size and font name

This is what i have tried,
UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = #"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;//Here i am adjusting the textview
[self.view addSubview:_textView];
Basically after fitting the text into textview,scrolling is enable,but i cannot view the content inside the textview without scrolling the textview.I do want to initialize the UITextView frame size based on the text size,font name etc.
Any solution is appreciated.Thanks.
NSString *str = #"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
UIFont * myFont = [UIFont fontWithName:#"your font Name"size:12];//specify your font details here
//then calculate the required height for the above text.
CGSize textviewSize = [str sizeWithFont:myFont constrainedToSize:CGSizeMake(300, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
//initialize your textview based on the height you got from the above
UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, textviewSize.width, textviewSize.height)];
_textView.text = str;
[self.view addSubview:_textView];
And also you want to disable the scrolling in textview then refer this.
As William Jockusch states in his answer here:
You can disable almost all scrolling by putting the following method
into your UITextView subclass:
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
// do nothing
}
The reason I say "almost" all scrolling is that even with the above,
it still accepts user scrolls. Though you could disable those by
setting self.scrollEnabled to NO.
If you want to only disable some scrolls, then make an ivar, lets call
it acceptScrolls, to determine whether you want to allow scrolling or
not. Then your scrollRectToVisible method can look like this:
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated {
if (self.acceptScrolls)
[super scrollRectToVisible: rect animated: animated];
}

UITextView dynamically resizing text box / cell

I'm loading my UITextView from an XML feed so the text is constantly changing. I'm trying the following to resize the cell and text, and it resizes the cell but not the text view, it's just not displaying the text view, or sometimes just part of it.
Any tips along the right way will be really appreciated;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
AssessObject *newObj1;
newObj1=[totalArray objectAtIndex:indexPath.row];
NSString *cellText = newObj1.routeText;
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:16.0];
CGSize constraintSize = CGSizeMake(188.0, CGFLOAT_MAX);
CGSize textViewSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return textViewSize.height + 200;
}
Check the AutoresizingMask of the UITextView you have added to your cell.
Make sure it is set so that it resizes with the cell (you can do this either in IB, or via code using the UIViewAutoresizingMaskFlexibleWidth|UIViewAutoresizingMaskFlexibleWidth value)
Set the textView size equal to textView's contentSize.
Something like this:
CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, textView.contentSize.height);
I'm making the height of the textView equal to the height of it's contentView.
setup the font size, text content and frame rect of the UITextView, then [UITextView sizeToFit] to calculate the contentSize of UITextView, then calculate the row height with the size of contentSize.
Don't forget to resize the frame rect of UITextView;
I have used Bruno's idea to resize my TextView according to the amount of text, when I put it to the ScrollView. This is how I do this. A bunch of constants there, that you may not use. It is important to resize textView after adding it to the ScrollView.
// Programmatic creation of scroll view layout
NSString *text = #"Your text";
CGFloat textOffSetInColumn = 10;
CGFloat infoTextWidth = 196;
CGFloat infoOffsetVertical = 36;
CGFloat initialTextHeight = 50;
// Create textView with initial height
CGRect infoTextFrame = CGRectMake(textOffSetInColumn, infoOffsetVertical, infoTextWidth, initialTextHeight);
infoTextView = [[UITextView alloc] initWithFrame:infoTextFrame];
infoTextView.text = text;
[scrollView addSubview:infoTextView];
// Resize textView
CGFloat infoTextHeight = infoTextView.contentSize.height;
infoTextFrame = CGRectMake(textOffSetInColumn, infoOffsetVertical, infoTextWidth, infoTextHeight);
infoTextView.frame = infoTextFrame;
If you want to change the size of TextView and center it to the previous center, you can use this code:
// Changing size of TextView and centering
CGPoint center = self.categoryTextView.center;
self.categoryTextView.frame = CGRectMake(_categoryTextView.frame.origin.x, _categoryTextView.frame.origin.y, _categoryTextView.frame.size.width, _categoryTextView.contentSize.height);
self.categoryTextView.center = center;
Instead of categoryTextView use your own Outlet name.

How to split text into separate UITextView pages?

A subquestion is:
How do I determine what the built-in internal margins of a UITextview are?
I have a long master string of text that I am trying to split into separate UITextView pages that I can then scroll from page to page inside a UIScrollView. I use the following method to determine what the height of a string in a UITextView is and whether the string is over the height limit:
-(NSNumber *)getHeightByWidth: (NSString *) myString
mySize: (UIFont *) mySize
myWidth: (NSNumber *) myWidth
{
int intMyWidth = [myWidth intValue];
CGSize boundingSize = CGSizeMake(intMyWidth, CGFLOAT_MAX);
CGSize requiredSize = [myString sizeWithFont:mySize constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
NSNumber *retNumber = [[NSNumber alloc] initWithFloat:requiredSize.height];
return retNumber;
[retNumber release];
}
I call the getHeightByWidth method using the following cellFont as the input for mySize:
UIFont *cellFont = [UIFont fontWithName:#"Arial" size:14.0];
The UITextView is 320 pixels wide, but I notice that the text doesn't go from the left edge to the right edge as there are internal margins which look to be around 10 pixels on each side. So when I call getHeightByWidth I set myWidth = (320 - 10 - 10); But after building strings to fit within the UITextView, there are usually gaps on the last row that could be filled with the next words in the master string.
Can anyone tell me why these gaps on the last row of the text occur using this process for UITextView?
The built-in margins are represented by the property contentInset.
Also you can configure the margins yourself.
If you have your text view in IB, look for Content insets. The values must be 0, but it still displays some margin. Trying setting them to negative values such as -4 or -8.
In the code, do something like-
myTextView.contentInset = UIEdgeInsetsMake(-4,-8,0,0);
You have to set these values according to what you find suitable.

NSString sizeWithFont: for multiple lines?

Is there an equivalent to NSString's sizeWithFont: method that can be used for calculating the height of text in a UITectView for a given width? All of the methods from NSString only operate on a single line from what I can tell.
From Apple's reference for these NSString methods, you could use -sizeWithFont:constrainedToSize: or -sizeWithFont:constrainedToSize:lineBreakMode: for "Computing Metrics for Multiple Lines of Text".
CGSize size = [theString sizeWithFont:font
constrainedToSize:CGSizeMake(width, 100000)];
return size.height;
For UITextView, all you have to do is call -sizeToFit on the view, and it will automatically resize its height until it can fit all the text available. All you need to do is set the width of the text view, set the text, then call -sizeToFit. The text view will resize its height just enough to fit all the text.
UPDATE:
Apparently text views only shrink when there's excess height, but they don't grow if there's insufficient height to display all the text. In addition, once you call -sizeToFit, the text view's y coordinate is reset back to 0.0f. So here's what you do:
CGFloat textViewWidth = 300.0f;
CGFloat textViewPadding = 10.0f;
UITextView * textView = [[[UITextView alloc] init] autorelease];
textView.text = ...; // Really long string
textView.frame = CGRectMake(0.0f, 0.0f, textViewWidth, CGFLOAT_MAX);
[textView sizeToFit]; // Shrinks the height to fit all the text
textView.frame = CGRectMake(textViewPadding, textViewPadding,
textViewWidth, textView.frame.size.height);
[self.view addSubview:textView];
First, you set the frame just so you can set the width like you want it. You use CGFLOAT_MAX to pretty much indicate infinite height. Next, calling -sizeToFit shrinks the height until it just fits all the text. However, it also resets the y coordinate, so we go ahead and set the frame again to configure the x and y coordinates—in this example, 10.0f for both x and y—, leaving the width alone and keeping the height set to whatever -sizeToFit calculated.
actually, you could use the property contentSize.