what to use instead of scrollRangeToVisible in iOS7 or TextKit - ios

In previous versions of iOS, my UITextView will scroll to the bottom using
[displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])];
or
CGFloat topCorrect = displayText.contentSize.height -[displayText bounds].size.height;
topCorrect = (topCorrect<0.0?0.0:topCorrect);
displayText.contentOffset = (CGPoint){.x=0, .y=topCorrect};
But the former will now have the weird effect of starting at the top of a long length of text and animating the scroll to the bottom each time I append text to the view. Is there a way to pop down to the bottom of the text when I add text?

textView.scrollEnabled = NO;
[textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1,0)];
textView.scrollEnabled = YES;
This really works for me in iOS 7.1.2.

For future travelers, building off of #mikeho's post, I found something that worked wonders for me, but is a bit simpler.
1) Be sure your UITextView's contentInsets are properly set & your textView is already firstResponder() before doing this.
2) After my the insets are ready to go, and the cursor is active, I call the following function:
private func scrollToCursorPosition() {
let caret = textView.caretRectForPosition(textView.selectedTextRange!.start)
let keyboardTopBorder = textView.bounds.size.height - keyboardHeight!
// Remember, the y-scale starts in the upper-left hand corner at "0", then gets
// larger as you go down the screen from top-to-bottom. Therefore, the caret.origin.y
// being larger than keyboardTopBorder indicates that the caret sits below the
// keyboardTopBorder, and the textView needs to scroll to the position.
if caret.origin.y > keyboardTopBorder {
textView.scrollRectToVisible(caret, animated: true)
}
}

I believe this is a bug in iOS 7. Toggling scrollEnabled on the UITextView seems to fix it:
[displayText scrollRangeToVisible:NSMakeRange(0,[displayText.text length])];
displayText.scrollEnabled = NO;
displayText.scrollEnabled = YES;

I think your parameters are reversed in NSMakeRange. Location is the first one, then how many you want to select (length).
NSMakeRange(0,[displayText.text length])
...would create a selection starting with the 0th (first?) character and going the entire length of the string. To scroll to the bottom you probably just want to select a single character at the end.
This is working for me in iOS SDK 7.1 with Xcdoe 5.1.1.
[textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1,0)];
textView.scrollEnabled = NO;
textView.scrollEnabled = YES;
I do this as I add text programmatically, and the text views stays at the bottom like Terminal or command line output.

The best way is to set the bounds for the UITextView. It does not trigger scrolling and has an immediate effect of repositioning what is visible. You can do this by finding the location of the caret and then repositioning:
- (void)userInsertingNewText {
UITextView *textView;
// find out where the caret is located
CGRect caret = [textView caretRectForPosition:textView.selectedTextRange.start];
// there are insets that offset the text, so make sure we use that to determine the actual text height
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;
// only set the offset if the caret is out of view
if (textViewHeight < caret.origin.y) {
[self repositionScrollView:textView newOffset:CGPointMake(0, caret.origin.y - textViewHeight)];
}
}
/**
This method allows for changing of the content offset for a UIScrollView without triggering the scrollViewDidScroll: delegate method.
*/
- (void)repositionScrollView:(UIScrollView *)scrollView newOffset:(CGPoint)offset {
CGRect scrollBounds = scrollView.bounds;
scrollBounds.origin = offset;
scrollView.bounds = scrollBounds;
}

Related

UISearchBar - internal UITextField height issue

I'm working on an app where I place a UISearchBar at the top of a UIViewController that contains a UITableViewController. The UISearchBar filters the contents of the UITableView.
I've left things alone so far (aside from customizing the colors to match my app's theme, which was hard enough!), but on anything except iPhone 4/5, the UISearchBar is dramatically too small.
Therefore, I'm trying to update the size of the font and the height of the internal UITextField.
All of this has proved remarkably difficult to accomplish, requiring quite a bit of customization. So, if you know of a library that makes this easier, please let me know in the comments.
Here's the code I'm using right now:
// In a category for UISearchBar
- (void)setup {
self.tintColor = [UIColor offWhite];
for (UIView *view in self.subviews) {
[self configureView:view];
}
}
- (void)configureView:(UIView *)view {
if ([view isKindOfClass:[UITextField class]]) {
CGFloat fontSize, frameHeight;
if (IS_IPHONE_4) {
fontSize = 14.0f;
frameHeight = 24.0f;
} else if (IS_IPHONE_5) {
fontSize = 14.0f;
frameHeight = 24.0f;
} else if (IS_IPHONE_6) {
fontSize = 17.0f;
frameHeight = 28.0f;
} else if (IS_IPHONE_6PLUS) {
fontSize = 20.0f;
frameHeight = 32.0f;
} else {
// iPad
fontSize = 24.0f;
frameHeight = 36.0f;
}
UITextField *textfield = (UITextField *)view;
textfield.font = [UIFont buttonFontOfSize:fontSize];
textfield.textColor = [UIColor offWhite];
textfield.tintColor = [UIColor offWhite];
CGRect frame = textfield.frame;
frame.origin.y = (self.frame.size.height - frameHeight) / 2.0f;
frame.size.height = frameHeight;
textfield.frame = frame;
}
if (view.subviews.count > 0) {
for (UIView *subview in view.subviews) {
[self configureView:subview];
}
}
}
Note: I structured my code this way in case Apple changes the internal structure of the UISearchBar. I didn't want to hard-code index values.
So, this code "works", in that the end result is what I desire, namely, a taller UISearchBar with text sized as specified and the internal UITextField also taller, as specified. What I don't understand is the process of getting there.
If I call [self.searchBar setup] in my general AutoLayout process, it doesn't work (the internal UITextField is the wrong height). This makes sense to me, since the frame is (0,0,0,0) until the view is actually laid out.
If I call [self.searchBar setup] in my -viewWillAppear: method, it doesn't work (the internal UITextField is the wrong height). This doesn't make sense to me, since debugging shows the frames to still be (0,0,0,0), but I thought -viewWillAppear: was called when everything was laid out and set up.
If I call [self.searchBar setup] in my -viewDidLayoutSubviews method, it "works", but the internal UITextField starts out the "normal" height and then "jumps" to the correct height some time after the view actually appears.
I set up the entire UIViewController in code, using pure AutoLayout. I simply cannot get the UISearchBar set up the way I want BEFORE the view finished loading and is displayed on screen. I've seen some funky stuff in the past, but I've always been able to force a view to render as desired. Is there something special behind the scenes with UISearchBar? Does anybody know how to get this done?
You're mixing auto-layout and manual layout (someView.frame = …) on the same view. You can't do that.
Instead, to change the height, set the constant on your view's height constraint to frameHeight. Let the auto-layout engine set the frame for you.

How to shift subview of UITextView by size of one line when cursor goes to next line?

I have a textView and I added an image to this textView. When i write text and go to next line I want to shift this image down by size of one line.. Similar like in twitter app when you create a tweet with picture. In this code I can shift picture by line, but my problem is it shifts to late (only on second symbol of next line).. I tried to use different values in CGSizeMake but line was shifted too early or too late.. Any recommendations?
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
CGSize constrainedSize = CGSizeMake(self.textView.contentSize.width, self.textView.contentSize.height);
UIFont *fontText = [UIFont systemFontOfSize:17];
CGRect textRect = [textView.text boundingRectWithSize:constrainedSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:fontText}
context:nil];
size = textRect.size;
CGFloat height = ceilf(size.height);
CGFloat width = ceilf(size.width);
CGRect frame = CGRectMake(0.0f, height+50, 100.0f, 100);
_imageView.frame=frame;
return YES;
}
You are hardcoding your font size. Maybe the text field has a different font. Use textField.font instead.
Also, you should simplify your code and eliminate the unused variables, such as width.
Finally, you should set a breakpoint where you calculate the size and keep checking if it is correct. Based on that it should be easy to debug.
Also, please note that textField.text does not yet contain the text that is going to be added. Before checking the size, you would have to first construct the new resulting string yourself.
NSString *newText = [textField.text
stringByReplacingCharactersInRange:range withString:text];
I think you should add your Image as subview to superview of your textView.
In shouldChangeTextInRange: fit frame of textView to content of textView.
Then just use KVO for catch moments, when frame of textView was changed. So, now you can keep top border of image on bottom border of textview, even animated!
I wont write code instead you, but it sound very easily and interesting, right?

iOS7 UITextView scrollEnabled=YES height

I am doing a test project, and came across a problem with UITextView.
I am dynamically getting the content size of the text in the text view, and then increasing its height when needed. When the height reaches the threshold I have set, I will set scrollEnabled = YES to enable scrolling. Weird thing seems to happen as shown in the following screen shots:
Before going to new line and enabling scrolling:
After entering the next character, which will enable the scrolling:
After that, entering another character again, the text view will become normal again with scroll enabled (in fact the height remains as in the previous screen shot, I change the height according to content size, so it become the same height before enable scroll):
Anyone has came across this problem and able to solve it? If this is an iOS7 bug, any other suggestion for creating a message input text box? I wonder if previous iOS versions have this problem though.
Edited:
It seems like this problem occurs when the textview's scrollEnabled is YES and change the textview.frame.size.height, then the height will reset to the initial height (as in the height set in Interface Builder). Wonder if this will help for this problem.
The following shows the code used for editing the height of the text view (it is a method for the selector which will be called upon received UITextViewTextDidChangeNotification):
NSInteger maxInputFieldWidth = self.inputTextField.frame.size.width;
CGSize maxSize = CGSizeMake(maxInputFieldWidth, 9999);
CGSize neededSize = [self.inputTextField sizeThatFits:maxSize];
NSInteger neededHeight = neededSize.height;
if (self.inputTextField.hasText)
{
[self.inputTextField scrollRangeToVisible:NSMakeRange([self.inputTextField.text length], 0)];
if (neededHeight <= TEXTVIEW_MAX_HEIGHT_IN_USE && neededHeight != previousHeight)
{
previousHeight = neededHeight;
CGRect inputTextFieldFrame = self.inputTextField.frame;
inputTextFieldFrame.size.height = neededHeight;
inputTextFieldFrame.origin.y = TEXTVIEW_ORIGIN_Y;
self.inputTextField.frame = inputTextFieldFrame;
}
else if (neededSize.height > TEXTVIEW_MAX_HEIGHT_IN_USE)
{
if (!self.inputTextField.scrollEnabled)
{
self.inputTextField.scrollEnabled = YES;
CGRect inputTextFieldFrame = self.inputTextField.frame;
inputTextFieldFrame.size.height = TEXTVIEW_MAX_HEIGHT_IN_USE;
inputTextFieldFrame.origin.y = TEXTVIEW_ORIGIN_Y;
self.inputTextField.frame = inputTextFieldFrame;
}
else if (neededHeight != previousHeight)
{
previousHeight = neededHeight;
CGRect inputTextFieldFrame = self.inputTextField.frame;
inputTextFieldFrame.size.height = TEXTVIEW_MAX_HEIGHT_IN_USE;
inputTextFieldFrame.origin.y = TEXTVIEW_ORIGIN_Y;
self.inputTextField.frame = inputTextFieldFrame;
}
}
}
Over a year later and scrollEnabled is still causing problems. I had a similar issue where setting scrollEnabled = true (I'm using Swift) would not cause any changes.
I solved the problem by setting autolayout constraints on all sides of the textView. Then, like you detailed here, I just set textView.frame again. My guess is that this causes some internal update, which actually turns scrolling on. I'm also guessing that autolayout then forces the textView to stay at the right height, as opposed to the collapse that you're experiencing.
The brilliant Pete Steinberger has had a lot of problems with the UITextView and implemented a lot of fixes as a result.
His article can be found here with links to his code.
For a direct link to the code, it can be found here, but I recommend reading the post.
I ran into a similar issue (I'm using auto-layout) and was able to solve it with the following set up:
Adding top, leading, bottom, trailing margin constraints to my text view
Adding a greater-than-or-equal-to minimum height constraint with priority 999 (in my case this was set to 50)
Adding a less-than-or-equal-to maximum height constraint with priority 1000 (in my case this was set to 125)
Adding an equal-to height constraint with priority 1000 (set to 125) and making sure it's not installed (uncheck the 'installed' option in Interface Builder or set 'active' to NO/false on the constraint in code)
I then use the following code to determine the height of the text view and enable/disable scroll and constraints:
- (void)textViewDidChange:(UITextView *)textView {
...
CGSize size = textView.bounds.size;
CGSize newSize = [textView sizeThatFits:CGSizeMake(size.width, CGFLOAT_MAX)];
if (newSize.height >= self.textViewMaxHeightConstraint.constant
&& !textView.scrollEnabled) {
textView.scrollEnabled = YES;
self.textViewHeightConstraint.active = YES;
} else if (newSize.height < self.textViewMaxHeightConstraint.constant
&& textView.scrollEnabled) {
textView.scrollEnabled = NO;
self.textViewHeightConstraint.active = NO;
}
...
}
Using sizeThatFits: to determine the desired size of the text view, I either set scroll enabled or disabled. If it's enabled, I set the height constraint to active to force the text view to stay at the desired height.

iOS autolayout with resize

I have two views one is textView and below it is a scrollview, in my application the textView should toggle expand when touch it.I set the "Top Space to: Text View" for scrollView in IB.But When I expand the textView it seems not work.
here is the toggle expand code.
- (void)onTextViewClicked:(id)sender
{
CGRect targetFrame = _descTextView.frame;
if (_isTextViewExpand) {
targetFrame.size.height = _descTextViewNormalHeight;
_descTextView.frame = targetFrame;
_isTextViewExpand = NO;
[_contentScrollView setContentSize:CGSizeMake(320.f, kContentScrollViewDefaultHeight)];
}
else {
targetFrame.size.height = _descTextViewExpandHeight;
_descTextView.frame = targetFrame;
_isTextViewExpand = YES;
[_contentScrollView setContentSize:CGSizeMake(320.f, kContentScrollViewDefaultHeight + ( _descTextViewExpandHeight - _descTextViewNormalHeight ))];
}
}
You need a different approach entirely. With Auto Layout, you should never call -setFrame:. If you want the views to grow you should add a constraint or edit one of the existing constraints and then call either -setNeedsUpdateConstraints or -layoutIfNeeded.
Or just turn off Auto Layout.

Split the full contents of cell between UILabel and UIButton

I've got a subclassed UITableViewCell. I'm dynamically adding a UILabel and UIButton to it.
Right now I've overridden layoutSubviews and am setting the x,y absolutely of the button and label. To be able to accommodate both screen layouts as well as larger screens I'd like to make this automatic. Is there a way to tell the label to "float left" and the button to "float right?" Ideally the label should use up all space that the button doesn't need (the button is going to be a fixed size for the most part).
this property of uiview should get you started
You can try something like this assuming cellLbl is the UILabel and cellBtn is the UIButton:
- (void) layoutSubviews
{
CGRect rctFrm;
CGFloat flW;
CGFloat flH;
int iSpacing = 4; // This could be fixed for a percentage of cell width
[super layoutSubviews];
flW = self.contentView.bounds.size.width;
flH = self.contentView.bounds.size.height;
rctFrm = self.cellBtn.frame;
flW -= rctFrm.size.width + iSpacing;
rctFrm.origin.x = flW; // Right justify button
rctFrm.origin.y = (flH - rctFrm.size.height) / 2; // Center button vertically
[self.cellBtn setFrame:rctFrm];
rctFrm = self.cellLbl.frame;
rctFrm.origin.x = iSpacing;
rctFrm.size.width = flW - (2 * iSpacing);
// You can adjust UILabel vertical position and height if desired
[self.cellLbl setFrame:rctFrm];
}

Resources