How to limit the content in UITextView in ios

前端 未结 7 2244
迷失自我
迷失自我 2021-02-08 11:56

I want to load long text in TextViews of different Views. The text should be divided to pages when it reaches end of the textviews. And the next textview must start with the con

7条回答
  •  伪装坚强ぢ
    2021-02-08 12:29

    I had to do measurements of text in a UITextView a while ago for overlaying views on top of some words in a UITextView on iOS 5. With the UITextView changes for iOS 7 I no longer have to do this. The way I did measurement may be what you need to break up your text. I don't have a good working code to give so I will have to describe the algorithm as best I can remember it.

    This algorithm does not work when there are variable line heights.

    1. I found by trial error that the text width I needed to match against was the width of the text view minus 16.
    2. Do a binary search on substrings of the text to find the maximum substring that fits in the UITexView where the substring breaks at word boundaries. You can use NSLinguistic tagger to get word boundaries.
    3. On each of the substring call [substr sizeWithFont:font constrainedToSize:sizeConstraint lineBreakMode:NSLineBreakByWordWrapping] where the size constraints in the width from step 1 and a very large height.
    4. You will need to continue the search until you can identify the word boundary where the size with constraints for word1 gives you a height that fits in your view and the immediately next word gives you a height that does not fit in your view. You will know that this is where the UITextView will do word wrapping that would be too big to fit on one of your pages.
    5. Break your text on the word boundary from step 4 and do the same for the next page.

提交回复
热议问题