0

UITextView exposes its NSLayoutManager, allowing clients to add custom styling as text is edited (e.g. this article implements a UITextView with syntax highlighting: http://www.objc.io/issue-5/getting-to-know-textkit.html)

Is there a way to get the underlying NSLayoutManager for UITextField to allow for similar customization?

2 Answers2

0

Apple does not expose the layoutManager for UILabel for various reasons. I heard that the reason for this is that it is actually shared between multiple labels because you don't edit label text, but only layout it infrequently, like when the bounds change.

But you can have the UILabel use a custom TextKit stack, like I show here: https://www.cocoanetics.com/2015/03/customizing-uilabel-hyperlinks/

Cocoanetics
  • 8,171
  • 2
  • 30
  • 57
-3

You can access the layout manager with textView.layoutManager. You can assign your own layout manager by creating all the objects yourself:

NSTextStorage* textStorage = [[NSTextStorage alloc] initWithString:string];

// you could create a subclass of NSLayoutManager here
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];

self.textContainer = [[NSTextContainer alloc] initWithSize:self.view.bounds.size];
[layoutManager addTextContainer:self.textContainer];

UITextView* textView = [[UITextView alloc] initWithFrame:self.view.bounds textContainer:self.textContainer];
[self.view addSubview:textView];

However if you're trying to do syntax highlighting that is not the approach I would take. I suggest subclassing UITextView to detect changes made by the user, and adding your own syntax highlighting at that point via [self.storage addAttributes:range:]

It probably would not be very hard to port this class I wrote from OS X to iOS: https://github.com/abhibeckert/Dux/blob/master/Dux/DuxSyntaxHighlighter.m — it applies syntax highlighting to an NSTextStorage, with good performance and support for a variety of languages.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • 2
    That wasn't the question. The question was whether or not it is possible to access the layoutManager for UITextField. – ldoogy Apr 24 '16 at 04:07