How can I tell UITextView to set the cursor to a particular line (line 13, for example) when it appears?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
UITextView has a method setSelectedRange: (NSRange) range.
If you know where in the string line 13 occurs, say location 237, then do: [textView setSelectedRange: NSMakeRange(237,0)];
If you need to find out where line 13 occurs, you’ve more work ahead. I’d start by looking at sizeWithFont, remembering to nip about 16 points off the width of your textView so that iOS gets the sums right. (That said, if you have line breaks, then just find the location of the 13th (or nth) “\n”.)
Update following your further query in the comment
There are lots of ways of finding the position of the nth \n. The following snippet isn’t pretty, but it will do the job. You could also use rangeOfString and iterate through the “\n”. In this snippet, if the target line is greater than the number of lines, it puts the cursor at the end. The code here assumes you have a UITextView property called userEntry.