How to let TextView be able to scroll horizontally

前端 未结 4 1262
心在旅途
心在旅途 2020-12-31 12:38

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

4条回答
  •  無奈伤痛
    2020-12-31 13:15

    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]

提交回复
热议问题