Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When creating a series of NSTextContainers, how do I specify container breaks based on the text content?

Tags:

ios

swift

textkit

I'm creating a series of NSTextContainers to hold the text from an HTML resource. I am able to add the HTML to an attributed string, assign that to a NSTextStorage and NSLayoutManager, and create a series of NSTextContainers to hold all the text.

My problem is, I want to add "page breaks" within the text, i.e. stop filling this text container and start another... In the documentation, I've found something call NSControlCharacterContainerBreakAction; but I'm unclear how to implement it or if thats even the best approach.

Code snippet below is how I'm current building by text containers (in Swift).

var myLayoutManager = NSLayoutManager()
var myText:NSAttributedString = {
        let path = NSBundle.mainBundle().URLForResource("localfile", withExtension: "html")
        let opts = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
        return NSMutableAttributedString(fileURL: path, options: nil, documentAttributes: nil, error: nil)!
        }()

myTextStorage = NSTextStorage(attributedString: myText)
myTextStorage.addLayoutManager(myLayoutManager)

//Create all textContainers to hold text
if myLayoutManager.textContainers.count == 0 {
    var range = NSMakeRange(0, 0)
    while(NSMaxRange(range) < myLayoutManager.numberOfGlyphs) {
        var myTextContainer = NSTextContainer(size: CGSizeMake(450, 580))
        myLayoutManager.addTextContainer(myTextContainer)
        range = myLayoutManager.glyphRangeForTextContainer(myTextContainer)
    }
}
like image 951
user797892 Avatar asked Oct 25 '25 04:10

user797892


1 Answers

You can just put "Page Break" ASCII control character in your string, layout manager will handle it.

let pageBreakString = String(UnicodeScalar(12))

Reference: ASCII Control Character

like image 160
elprup Avatar answered Oct 26 '25 18:10

elprup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!