0

I want to enable scrolling in the textview if the number of lines exceeds 5 otherwise there should not be any scrolling. Is that possible and how to achieve that?

Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

1

UITextView inherits from UIScrollView which has a property called scrollEnabled

You can add register your class as the UITextViewDelegate and implement the method

- (void)textViewDidChange:(UITextView *)textView

Then from the textView object get the text property, and check to see how many newlines/carriage returns there are. If there are more than 5, then set scrollEnabled to YES

UPDATE:

Take a look at NSString UIKit Additions, there are some methods in this class that allow you to get the CGSize of your NSString, specifically sizeWithFont:constrainedToSize:lineBreakMode:

Using this you should be able to enable scrolling once the CGSize reaches a height equivalent or greater than 5 lines of text calculated by uifont.lineHeight*5

Chris Wagner
  • 20,773
  • 8
  • 74
  • 95
  • Thats a good idea but when text is wrapped by frame of textview how will I come to know the number of lines? – Abhinav Apr 29 '11 at 20:50
  • @Flash: I tries using it but for a data of 8 lines in my text view this methos is returning me a count of 5. Important thing is that I have some 7 \n characters in the data. – Abhinav Apr 29 '11 at 21:58
  • Did you use the property lineBreakMode so that the new lines are caught? – Chris Wagner Apr 29 '11 at 22:51
  • Take a look at this SO Answer, http://stackoverflow.com/questions/50467/how-do-i-size-a-uitextview-to-its-content/526227#526227 – Chris Wagner Apr 29 '11 at 22:53
  • @Flash: The problem is string is not yet drawn on the screen. I am getting this data from server and for some functionality have to calculate in how many lines this will fit in a given size text area. Probably the methods shared by you are useful when you are retrieving the string from the UI. – Abhinav Apr 30 '11 at 01:52
  • You should be able to use a similar approach with these methods, once you get your response and you set your text property of the UITextField you could do the calculations and then manually trigger the UI update to resize the UITextField. Separate your concerns, 1. you need to resize the UITextField based on a string size (this problem's solution is outlined above) 2. you need to update the UI once you get the response from your server – Chris Wagner May 02 '11 at 16:37
-3

Try to use this code:

- (void)viewDidAppear:(BOOL)animated
{
    [self.tableView reloadData];
    if([myDataSourceArray count] < 6)
    {
        self.tableView.scrollEnabled = NO;
    }
    else
    {
        self.tableView.scrollEnabled = YES;
    }
}
albianto
  • 4,092
  • 2
  • 36
  • 54
  • viewDidAppear will only get called once, so even if this did work it wouldn't be dynamic when a user is typing. Also he is not using a `UITableView` as stated he is using `UITextView` – Chris Wagner Apr 29 '11 at 21:47