Oleg Tretiakov
Oleg Tretiakov

Reputation: 159

UIPageViewController/TextKit count number of pages

How can I count the number of pages of text if I have a very long NSTextStorage and I know CGSize of NSTextContainer? Is there a standard procedure for this thing or some way to count it dynamically? I can't find a good tutorial to make an iBooks like book from raw text with custom fonts (I need to draw texts of 20-50 pages).

Upvotes: 0

Views: 476

Answers (1)

Oleg Tretiakov
Oleg Tretiakov

Reputation: 159

I found a good way to count a number of pages using TextKit's NSLayoutManager. Just count pages when I create NSTextContainers

    var range = NSMakeRange(0, 0)
    var containerIndex : UInt = 0
    var pageIndex : UInt = 1
    while(NSMaxRange(range) < layoutManager.numberOfGlyphs) {
        let textViewRect = self.frameForViewAtIndex(containerIndex)
        let containerSize = CGSizeMake(textViewRect.size.width, textViewRect.size.height - 16)
        let textContainer = NSTextContainer(size: containerSize)
        layoutManager.addTextContainer(textContainer)

        let textView = UITextView(frame: textViewRect, textContainer: textContainer)
        self.addSubview(textView)
        range = (layoutManager.glyphRangeForTextContainer(textContainer))

        containerIndex++;
        if containerIndex%columnCount == 0 { pageIndex++ }
    }

columnCount is the number of columns if you'll use multicolumn layout

frameForViewAtIndex returns CGRect for current textView inside scrollView

Upvotes: 1

Related Questions