Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let TextView be able to scroll horizontally

I know the TextView is embedded in a ScrollView. And if there is a fairly long String(Which contains no "\n")

The TextView will automatically do the line-wrap, according to the width of the TextView.

If TextView's height is short, then we are able to scroll it vertically. How do you disable the auto line-wrap? Such that, if there are no "\n" encounters, it does not line wrap. Rather, it lets the user scroll horizontally to view the text.

How can I implement this?

like image 807
Microos Avatar asked Oct 29 '15 06:10

Microos


1 Answers

I figure out how to do this with many helps of you guys :D, thanks, and here we go!

1. So, firstly, We need a longlonglong String, right?

let displayStr = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 "

2. Assume we have a UIScrollView which is linked by @IBOutlet or got by calling the .viewWithTag(xxx) .We will let it be named as scroll :

3. It's time to get the size of our string, here is a key function we'll use it:

Oh! I almost forget to define what kind of Font( this's a crucial parameter ) we will use, and What is the max-size of our string's size

let maxSize = CGSizeMake(9999, 9999)
let font = UIFont(name: "Menlo", size: 16)!
//key function is coming!!!
let strSize = (displayStr as NSString).boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : font], context: nil)

4. OK, now we can put the string into a textView, you need to programmatically create a new UITextView, so that we can define the frame which is identical to the string's size(Oh, maybe a little bigger :D) :

let frame = CGRectMake(0, 0, size.width+50, size.height+10)
let textView = UITextView(frame: frame)
textView.editable = false
textView.scrollEnabled = false//let textView becomes unScrollable
textView.font = font
textView.text = displayStr

5. Back to our scroll, we will set its contentSize:

scroll.contentSize = CGSizeMake(size.width, size.height)

6. Finally, addSubview: scroll.addSubview(textView)

You can see, textView is embed in a scrollView, which allow it to scroll with 2 directions.

B.T.W. My implement is just a demo for static String. if you want user to use a textView which will not line wrap if he doesn't input any "\n", you may need dynamically calculate the string size. :D

[I hope this will help]

like image 177
Microos Avatar answered Sep 23 '22 19:09

Microos