How to scroll to specific portion of an attributed string - ios

I have an NSMutableAttributedString that lives inside a UIScrollView. I highlight a portion of the string using the addAttributes:range: function.
When a lot of text is present, I currently have to manually scroll quite a ways to get to the highlighted part. I'd like to come up with a way to have the view automatically scroll to the highlighted portion when the view is loaded - sort of how you can use anchors to link to a specific part of a webpage.
I'm guessing there is a function that, given some kind of numbers will allow me to scroll to a specific part of my page? How might I come up with such numbers to provide to such a function? Using the NSRange component from the attributed string?
Perhaps there is better way to accomplish this?

UIScrollView has the method setContentOffset:animated: which would allow you to scroll to a particular point in your content. To figure out what the appropriate offset is, you would have to determine the width of the portion of your attributed string prior to the highlighted part. The documentation for the methods you use to do this can be found here. You could do this using the size method of NSAttributedString.
It would look something like this:
#interface SomeViewController : UIViewController
#end
#implementation SomeViewController {
UIScrollView* _scrollView;
}
- (void)scrollToOffset:(NSInteger)offset inAttributedString:(NSAttributedString*)attributedString {
NSAttributedString* attributedSubstring = [attributedString attributedSubstringFromRange:NSMakeRange(0, offset)];
CGFloat width = attributedSubstring.size.width;
[_scrollView setContentOffset:CGPointMake(width, 0.0f) animated:YES];
}
#end
The above code assumes that we're talking about a single line of text and that scrolls horizontally. Alternatively to do this for a fixed width that wraps to an arbitrary height you would need to calculate height with the following code (rather than attributedSubstring.size.height) and then possibly subtract a little to account for wanting to show the last line that of the substring:
CGFloat height = [attributedSubstring boundingRectWithSize:CGSizeMake(<#fixed width to wrap at#>, HUGE_VALF) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
[_scrollView setContentOffset:CGPointMake(0.0f, height) animated:YES];
This is similar to code I use when determining the height of table or collection view cells that have dynamic text that I need to accommodate.

I did not specify it in my original question, but I will address it here. The accepted answer above provides a solution when one wants to scroll horizontally to a specified portion of text. However, in order to scroll vertically a solution similar to that of below is required - other methods may exist but this is what worked for me.
Notice that instead of getting the size component from the attributed sub-string itself, we are getting the size from the view AFTER we've added the sub-string to it. We then insert the full string and force the scroll:
NSAttributedString* att_string = [[NSMutableAttributedString alloc] initWithString:mystring];
NSAttributedString* sub_string = [att_string attributedSubstringFromRange:NSMakeRange(0, highlight_begin_index)];
[the_view setAttributedText:attributedSubstring];
CGFloat jump_height = the_view.contentSize.height;
[the_view setAttributedText:att_string];
[the_view setContentOffset:CGPointMake(the_view.contentOffset.x,jump_height) animated:FALSE];

Related

Simply calling UITextView `sizeThatFits:` causes glitchy scrolling / input behavior?

I find that in iOS 8 using UITextView sizeThatFits: causes glitchy scrolling behavior. The Text View is constantly scrolling away from the line you are typing on. It seems to be scrolling to the top of the view and then back again.
If it matters, the view is set as an inputAccessoryView.
Via the keyboard I'll type: 1 return 2 return 3 return 4
The TextView the moment before I type 4:
In the delegate method I call sizeThatFits:.
- (void)textViewDidChange:(UITextView *)textView {
[textView sizeThatFits:CGSizeMake(100, 100)];
}
TextView scrolls up to the top. Input happens below the view. Jittery, glitchy scrolling movement up to the top and then back to your line as you type. Input occurs under the keyboard. Extremely annoying.
If I comment out the line:
//[textView sizeThatFits:CGSizeMake(100, 100)];
Now when I type 4 we have nice, smooth typing on the last line:
The UIScrollView sizeThatFits: docs state:
This method does not resize the receiver.
So I'm confused why this would have any effect on the scrolling/input of the textfield.
Is there any way to avoid this glitchy scrolling?
How can you calculate the "height that fits" for a Text View without hitting this bug?
I had the exact same problem and it took me 5 hours to solve this nasty apple bug, I wish I could send them an invoice!
What I end up doing was creating a copy of my original UItextView:
self.textViewCopy = [[UITextView alloc] initWithFrame:self.textView.frame];
[self.textViewCopy setFont:self.textView.font];
And don't add it as a subview.
Then instead call the sizeThatFits on the copy (which will screw up the copy which we don't care about and gets us the information we need):
[self.textViewCopy setText:self.textView.text];
CGSize size = [self.textViewCopy sizeThatFits:CGSizeMake(fixedWidth, CGFLOAT_MAX)];
Using the NSString method sizeWithFont:constrainedToSize: on the text within the UITextView seems to provide a performant alternative to sizeThatFits:.
CGSize preferredSize = [textView.text sizeWithFont:textView.font constrainedToSize:CGSizeMake(CGRectGetWidth(textView.bounds), 200.0)];
It's possible that sizeThatFits: is using sizeWithFont:constrainedToSize: under the hood. Regardless, the iOS glitchy scrolling bug is not reproduced when using the NSString method.

UITextView doesn't scroll sometimes

While typing in a UITextView sometimes it scrolls down to current line(case a) but it doesn't the other times(case b).
There's another problem which is:
The same UITextView sometimes show all the text in it (case 1) but other times it doesn't show the last line of text(case 2).
Whenever case 1 happens case a follows.
and Whenever case 2 happens case b follows.
This is the hierarchy of the view:
Size(variable height-fixed width) of these UITextViews as well as UICollectionViewCells are calculated using sizeWithFont:constrainedToSize:lineBreakMode:
Limits of height are set from 43 to 120.
if height>43 then enableScrolling is set to YES, otherwise to NO(Logic X).
Scrolling is enabled when textViewBeginEditing and Logic X is applied when textViewEnded Editing.
There is no scrolling in case 2.
Please suggest cause and workarounds.
On iOS7, I think that you could leave the UITextView's scrollEnabled property set to YES in all cases. If it contains less text it will just not scroll. If you set the property while configuring the cell, you might get this kind of weird behavior, because UIKit is reusing those cells and probably the UITextView too.
For making the last line visible, I'm guessing you need to calculate the text view size more accurately. Try using the attributedText to set the text, with all the formatting you need. Then, in order to calculate the size, you can do it like this:
NSAttributedString *text = self.yourCellsTextView.attributedText;
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:text];
CGSize size = [calculationView sizeThatFits:CGSizeMake(self.yourCellsTextView.frame.size.width, FLT_MAX)];
CGFloat finalMessageHeight = size.height;
Hope this helps :).

UITextView text becomes invisible after height reaches 8192.0

I have a non-scrollable UITextView embedded in a UIScrollView and add text to the UITextView dynamically. The UIScrollView adjust it's contentSize accordingly based on the TextView's frame. However, once the UITextView exceeds a height of 8192, the text will become invisible (but still there, because you can use the magnifying glass to highlight text and even see parts of the text through the magnifying glass).
CGRect textviewFrame = self.TextView.frame;
textviewFrame.size.height = [self textViewHeightForAttributedText:self.TextView.attributedText andWidth:320.0];
self.TextView.frame = textviewFrame;
self.ScrollView.contentSize = self.TextView.frame.size;
Helper function to size UITextView accordingly:
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
UITextView *textView = [[UITextView alloc] init];
[textView setAttributedText:text];
CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
Didn't realize it was the same exact problem that was unsolved here until I tested it out explicitly by forcing the max size to 8193 and the problem occurred (while a max size of 8192 still had the text showing correctly). Anyone run into this problem before and know of a work around? Thanks
I was recently hit by this problem and have worked out an effective way around it. Although it seems like an iOS bug IMHO it's really not... there are practical limits to CALayer sizes, plus drawing an 8K high piece of text takes a long time. Much better to do as Apple intended and to only render the bit of text that's visible... that's why UITextView extends UIScrollView after all.
The problem is that UITextView isn't terribly easy to integrate with other bits of UI. In my case I am working on a news app where a single UITextView is used to render the article, plus there's some separate UI (titles and buttons etc) above and below it, all hosted in a single scrollable container.
The solution I've found is to split the UITextView into two views... a dedicated UITextView container whose frame is the full text size (i.e. the same size your UITextView's contentSize) and which is the superview of your UITextView. Your child UITextView's frame should be set to the bounds of the outer scrollable container.
Then all you have to do is use key-value observation to monitor the contentOffset property of your outer scrollable container view (in my case this is a UICollectionView). When its contentOffset changes you update (1) the contentOffset of your UITextView, and (2) the transform property of the UITextView's layer. By updating that transform property the UITextView is fixed to fill the currently-visible part of it's superview. But because you're also updating the UITextView's contentOffset, this trickery is totally invisible to the user... it looks and behaves as if the UITextView is simply very large.
Here's a fully functional solution, for anyone who'd like it!
** Assuming your content size will not exceed the limits of two text views **
This solution works by adding two UITextViews to your view, and splitting your text between them. It looks complicated, but it's actually very simple! I've just written a very verbose description :)
Step 1 - Add two UITextViews to your view:
I added mine in my storyboard. Place them so that one is directly above the other, with no space between them. Don't worry about setting the height (we will set that later).
Set constraints on the views so that they are tied to each other from the top and bottom, and the surrounding edges of the container from all other sides, including your desired padding. i.e. tie the first text view to the container from the top, left, and right, and to the second text view from the bottom. Tie the second text view to the container from the bottom, left, and right, and to the first text view from the top. This will ensure that they stretch appropriately when the content is set.
Don't set any constraints on the height of the views, or if you must (to avoid warnings from the constraints inspector), set the height of one of the views to be >= 20, or some similarly small number.
Disable scrolling, bouncing, and scrolling indicators for both your text views. This solution relies on the views being a fixed, non-scrollable height, so if you'd like your content to scroll, you should use a UIScrollView or UITableViewCell as a container.
Create outlets for your two new text views in your view controller file, naming them something like textView1 and textView2.
Step 2 - Set textContainerInsets to zero:
Set the textContainerInset property on both text views to zero, either using User Defined Runtime Attributes:
or code:
self.textView1.textContainerInset = UIEdgeInsetsZero;
self.textView2.textContainerInset = UIEdgeInsetsZero;
This will ensure that the no visible space will appear between the two views when the content is set, and should not affect the other spacing around your views.
Step 3 - Split your content, set it, and update the view heights:
Simply copy the following code into your view controller file (viewDidLoad), and set the contentString variable to your content.
/* Content is split across two UITextViews to avoid max drawing height */
NSString *contentString = #"Some very long piece of text...";
// Set text
NSArray *components = [contentString componentsSeparatedByString:#"\n"];
NSInteger halfLength = [components count] / 2;
NSArray *firstHalf = [components subarrayWithRange:NSMakeRange(0, halfLength)];
NSArray *secondHalf = [components subarrayWithRange:NSMakeRange(halfLength, [components count] - halfLength)];
NSString *contentString1 = [firstHalf componentsJoinedByString:#"\n"];
NSString *contentString2 = [secondHalf componentsJoinedByString:#"\n"];
self.textView1.text = contentString1;
self.textView2.text = contentString2;
// Set text view heights
CGFloat fixedWidth1 = self.textView1.frame.size.width;
CGFloat fixedWidth2 = self.textView2.frame.size.width;
CGSize newSize1 = [self.textView1 sizeThatFits:CGSizeMake(fixedWidth1, CGFLOAT_MAX)];
CGSize newSize2 = [self.textView2 sizeThatFits:CGSizeMake(fixedWidth2, CGFLOAT_MAX)];
CGRect newFrame1 = self.textView1.frame;
CGRect newFrame2 = self.textView2.frame;
newFrame1.size = CGSizeMake(fmaxf(newSize1.width, fixedWidth1), MIN(newSize1.height, 8192));
newFrame2.size = CGSizeMake(fmaxf(newSize2.width, fixedWidth2), MIN(newSize2.height, 8192));
self.textView1.frame = newFrame1;
self.textView2.frame = newFrame2;
This code splits the contentString roughly in the middle, looking for the nearest newline. If you'd like to split your content on a different character, simply change all occurrences of \n above to whatever you'd like to split on.
Step 4 - Set your container view height:
Set your container view (scrollView, tableViewCell, whatever else) to the height of your two text views, plus whatever additional space you've set above and below them.
CGRect viewFrame = self.myView.frame;
viewFrame.size.height = MIN(self.textView1.frame.size.height, 8192) + MIN(self.textView2.frame.size.height, 8192) + kTextViewContainerPadding;
[self.myView setFrame:viewFrame];
(In my code, kTextViewContainerPadding is a macro I've set to the sum of the space above and below my two text views, within their container).
That's it! Good luck.
Try enabling the scroll for the scrollView.
Keep the height of the textView > height of the content, so that in reality there will be no scroll, but scrollEnabled should be = YES
It solved the problem for me.
Hello I think am not late to answer. I got the same problem like you. This is my solution:
textView.scrollEnabled = YES;
contentTextView.attributedText = finalAttrString;
// contentTextView.text = [attrString string];
contentTextView.font = kFont(contentTextFS + [valueOfStepper intValue]);
[contentTextView sizeToFit];
contentTextView.height += 1;//This is the key code
//contentTextView.height = 8192.0f
Them I solved the trouble and I can change size dynamic.Successfull on iOS 8

how to make uitextview none scrollable but display all content

At the moment in my IB I have a View Controller which is covered by a UIScroll View. Within the scroll view I have a UIImageView at the top, a UILableView in the middile and a MKMapView at the bottom. The UILableView number of lines is set to 0 (infinite) and word wrap allowing me display as much content as I want.
I want to be able to tap telephone numbers and website url's for the content in my UILableView. The best way I've found so far is to change it to a UITextView which handles all of this for you. However... I can not get the same behaviour with the scrolling.
Before the image, label and map used to scroll as a block. Now, only the textView scrolls. Any advice appreciated.
the displaying part is correct, that is calculate the frame of the textView based on the size of its text for scrolling add this [textView setScrollEnabled:NO];
You can try using this project:
https://github.com/mattt/TTTAttributedLabel
label.dataDetectorTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed
label.delegate = self; // Delegate methods are called when the user taps on a link (see `TTTAttributedLabelDelegate` protocol)
label.text = #"Fork me on GitHub! (http://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked
NSRange range = [label.text rangeOfString:#"me"];
[label addLinkToURL:[NSURL URLWithString:#"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring

How to create a multi-line UILabel, with a maximum width?

I'm writing a simple IRC client that I'm modeling after Twitter's iOS app appearance. I've taken a screenshot of the Twitter app, for reference:
It looks like a simple table view with a few labels inside of each cell. So, in my app, I am programmatically creating a table and the cell formatting. My custom cell has only two labels in it, which I have positioned one on top of the other. The top label is a simple 1-liner. The bottom label I would like to contain longer messages, and need it to word-wrap to multiple lines while staying within my specified width.
How do I achieve this?
So far, I've tried explicitly setting the frame of the label to the dimensions that I want, but it does not word-wrap, if this is all I do. It just flows out of the cell horizontally. I then tried calling sizeToFit, within the tableView:cellForRowAtIndexPath: function, for this label, but it appears to word-wrap at a very small width - the text wraps after like two or three letters and then flows out of the cell vertically.
I can't seem to figure out how to get the text within the label to wrap after a specified width. Any ideas?
My custom cell class: https://github.com/ryancole/pound-client/blob/master/pound-client/views/MessageListCell.m
The cellForRowAtIndexPath function: https://github.com/ryancole/pound-client/blob/master/pound-client/controllers/MessageListViewController.m#L62-L84
Edit 1:
To demonstrate what happened when I set numberOfLines to 0, for unlimited, I have attached a screenshots of that being called. It wraps after a few characters, instead of first taking up the specified width of the UILabel's frame. This is being set prior to called sizeToFit.
You need to set numberOfLines to the number of lines you want, or 0 which allows for an unlimited number of lines (the default is 1). You might also need to set the lineBreakMode to NSLineBreakByWordWrapping (although that might be the default).
After Edit: If you want the text to start at the top, then I think you'll have to use variable height cells, and not set an explicit size for your custom cell. I did it this way in one of my projects:
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
UILabel *label = [[UILabel alloc] init];
label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = _objects[indexPath.row][#"detail2"];
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(300, 300000) lineBreakMode:NSLineBreakByWordWrapping];
CGFloat h = labelSize.height;
return h + 50;
}
The label I create here, is just for calculating the height of the row, it's discarded after this method ends. The width of the cell is determined by the 300 argument I have in the constrainedToSize: parameter. The +50 was just a fudge factor I added to get my cells looking right -- you'd probably want to mess with that number to get what you want. In my custom cell class, I used initWithStyle:reuseIdentifier, and didn't set any size.

Resources