iosmacostextview

Autosizing on {NS,UI}Textview works, but background colours leak outside the view


All,

I am programmatically creating NSTextView (and UITextView on iOS) objects on a canvas (just an {NS,UI}View. I am working on auto-resizing (which works), but there are some strange behaviours.

Here is what I want (and what I 95% achieve):

This all works (creating, moving, autosizing, styles, borders). For example, here is an initial text view just after creation.

Initial Creation

Here is some text being added and autosizing happening.

Typing and Autosizing

The Problem:

Where it gets weird is when I apply styles with a background color - then the TextContainers width shows up. Here is what it looks like when I apply a style with a background color.

Style with background color

I expected the NSTextView to crop the excess TextContent, but it does not.

Extra information:

The trick to make autosizing work is to set the TextContainer size to a large width, and turn off widthTracksTextView. This approach is outlined here: How to resize a NSTextView automatically as per its content? (complete with a video).

Here is the sizing initialization code from my NSTextView subclass:

VerticallyResizable = true;
HorizontallyResizable = true;
TextContainer.WidthTracksTextView = false;
TextContainer.HeightTracksTextView = false;
var s = TextContainer.Size;
s.Width = 1000;
TextContainer.Size = s;
MaxSize = new CGSize(1000, 10000);

Does anyone have any thoughts as to what I’m missing? Thx

Addendum

As far as I can tell, these are the best approaches:


Solution

  • The solution as provided by Willeke was to simply ensure that ClipsToBounds is set, and that it stays set. For some reason it gets reset after the constructor completes.

    Interestingly this is not needed on iOS which seems to have clip set to true.