As I look at it, NSAttributedString has some built-in measuring tools (AppKit additions) that you could use without having to resort to creating a layout manager, text container, etc. (In looking at the docs for NSTextContainer, I see that it wants to belong to a NSTextView, which is kind of missing in your code.) You could create substrings to measure the location of the fragment you want to highlight: one to measure from the start of the line to where you want to highlight (if your range start might not be zero) and one to measure the size of the box.
Be sure that you are measuring in the correct graphic context (that focus is locked on your field, which may be automatic depending on the method you are in). I suspect the discrepancy you are experiencing may have to do with the fact that your get container is not in any view, so its coördinates do not quite match with your field's view.