Applying transform to UITextView - prevent content resizing

谁都会走 提交于 2019-12-20 10:27:08

问题


When I apply a rotation transform to a UITextView and then click inside to begin editing, it appears that the content size is automatically being made wider. The new width of the content view is the width of the rotated view's bounding box. For example, given a text box of width 500 and height 400, and rotated by 30 degrees, the new content width would be:

(500 * cos(30)) + (400 * sin(30)) = 633

Or graphically:

Interestingly, if you are already editing the text view and THEN apply the transform, then it appears that no modification is made to the content size. So it appears that sometime around the start of text editing, the text view looks at its frame property and adjusts the content size based on the frame width. I imagine the solution to this is to tell it to use the bounds property instead, however I don't know where to do this, as I'm not sure exactly where the text view is deciding to modify the content size.

I have googled but can't seem to find any references to using transformed UITextViews. Does anybody have any ideas about this?

EDIT (button action from test project):

- (IBAction)rotateButtonTapped:(id)sender {
    if (CGAffineTransformIsIdentity(self.textView.transform)) {
        self.textView.transform = CGAffineTransformMakeRotation(30.0 * M_PI / 180.0);
    }
    else {
        self.textView.transform = CGAffineTransformIdentity;
    }

    NSLog(@"contentsize: %.0f, %.0f", textView.contentSize.width, textView.contentSize.height);
}

回答1:


I was also stuck with this problem.

The only solution which I found was to create an instance of UIView and add the UITextView as a subview. Then you can rotate the instance of UIView and UITextView will work just fine.

UITextView *myTextView = [[UITextView alloc] init];
[myTextView setFrame:CGRectMake(0, 0, 100, 100)];

UIView *myRotateView = [[UIView alloc] init];
[myRotateView setFrame:CGRectMake(20, 20, 100, 100)];
[myRotateView setBackgroundColor:[UIColor clearColor]];
[myRotateView addSubview:myTextView];

myRotateView.transform = CGAffineTransformMakeRotation(0.8);
[[self view] addSubview:myRotateView];



回答2:


Have you tried applying the rotation by doing a layer transform rather than a transform on the view?

#import <QuartzCore/QuartzCore.h>

mytextField.layer.transform = CATransform3DMakeRotation (angle, 0, 0, 1);

This might be enough to trick whatever broken logic exists inside the core text field code.



来源:https://stackoverflow.com/questions/6479727/applying-transform-to-uitextview-prevent-content-resizing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!