How can I make a UITextView scroll only when it is filled with text

I have this UITextViewone that works fine, but I can’t get the text inside UITextViewto start scrolling only after the size UITextViewis almost full, UITextView is 4 lines tall, but as soon as I reach the 2nd line, 1- I’m pushing the line up; I don’t want the view to start with scrolling until I reach the 5th line. scrollingEnabled = NOkeeps it from scrolling at all, so it didn't work.

UITextView *barf_ = [[UITextView alloc] initWithFrame:CGRectMake(20.0, 310.0, 155, 50)];

barf_.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);

//[barf_ scrollRangeToVisible:NSMakeRange([barf_.text length], 0)];

barf_.layer.cornerRadius = 3.0f;

barf_.layer.borderWidth = 0.5f;

barf_.font = [UIFont fontWithName:@"Helvetica" size:13];
+5
source share
4 answers

UITextView , scrollEnabled . self - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView

, . , , . , . :

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode

UIKit NSString. CGSize, , . -

CGSize textSize = [textView.text sizeWithFont:textView.font
                            constrainedToSize:CGSizeMake(textView.frame.size.width, MAXFLOAT)
                                lineBreakMode:UILineBreakModeWordWrap];
if (textSize.height > textView.frame.size.height) {
    textView.scrollEnabled = YES;
} else {
    textView.scrollEnabled = NO;
}
+2

, , textView, 32 .

YourTextView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0); shouldChangeTextInRange, !

+2

contentInset UITextView. , UITextView , , .

, , sizeWithFont, . , - iOS Development: Do Do It It Wrong, NSString , , a UIView . UIView, UILabel, UIButton .., , . UITextLabel .

:

# 2: - [NSString sizeWithFont:...]

iOS 7 promises UITextView , textContainerInset. ?

, , UITextView UIScrollView. , contentSize , view bounds, , .

contentSize bounds , , UIScrollView , , .

! 17.f. - - . , :

static const CGFloat kArbritaryHeight = 17.f;
CGFloat adjustedContentHeight = myTextView.contentSize.height - kArbritaryHeight;
CGFloat boundsHeight = CGRectGetHeight(myTextView.bounds);
BOOL tooMuchContent = adjustedContentHeight > boundsHeight;

if (tooMuchContent)
{
    myTextView.scrollEnabled = YES;
}
else
{
    myTextView.scrollEnabled = NO;
}
+2

You can use the method sizeWithFont:constrainedToSize:lineBreakMode:to check if your line will actually be displayed more than your text view, and see if you need to enable scrolling. You will need to call it at any time when the text in your scrollview is set.

Example:

CGSize barfStringSize = [barfString sizeWithFont:[barf_ font] 
                               constrainedToSize:CGSizeMake(barf_.bounds.size.width, MAXFLOAT) 
                                   lineBreakMode:UILineBreakModeWordWrap]
[barf_ setScrollEnabled:barfStringSize.height > barf_.bounds.size.height]
0
source

All Articles