UITextView textContainer exclusion path fails if full width and positioned at top of textContainer

放肆的年华 提交于 2019-11-30 11:46:34

This is an old bug.In the book Pushing the Limits iOS 7 Programming ,the author wrote this in page 377:

At the time of writing, Text Kit does not correctly handle some kinds of exclusion paths. In particular, if your exclusion paths would force some lines to be empty, the entire layout may fail. For example, if you attempt to lay out text in a circle this way, the top of the circle may be too small to include any text, and NSLayoutManager will silently fail. This limitation impacts all uses of NSTextContainer. Specifically, if lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect: ever returns an empty CGRect, the entire layout will fail.

Maybe you can override lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect: of your custom NSTextContainer to workaround.

I came across this problem as well. If you only need to exclude full width space at the top or bottom of the textView, you can use the textContainerInset.

Workaround suggestion:

Add a line break to your text.

textView.text = "\n" + textView.text

A quick workaround:

CGRect exclusionRect = [textView convertRect:imageView.bounds fromView:imageView];
if (exclusionRect.origin.x <= 0 && exclusionRect.origin.y <= 0 && exclusionRect.size.width >= textView.bounds.size.width) {
  exclusionRect.origin.x = 1;
  exclusionRect.origin.y = 1;
  exclusionRect.size.width -= 2;
}

Your image will still draw the same and unless you're using a font with glyphs that are 1px wide (I'm not even sure that's possible given kerning, etc), your exclusionRect will be guaranteed to be smaller than the full width.

I would be interested to know what kind of results you see if you allow your rect to be moved around in real-time. Attach a UIPanGestureRecognizer and update your exclusionRect as you pan around the screen. At what point does the text jump into the image?

Edit: If you're seeing problems until it is able to fit at least one character, maybe try adjusting your text frame.

if (exclusionRect.origin.x <= 0 && exclusionRect.origin.y <= 0 && exclusionRect.size.width >= textView.bounds.size.width) {
  frame.origin.y += CGRectGetMaxY(exclusionRect);
  frame.size.height -= CGRectGetMaxY(exclusionRect);
  [textView setFrame:frame];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!