UITextView在粘贴文本时可视地改变内容位置

And*_*rew 5 iphone objective-c uitextview ios

我有一个UITextView,它可以在需要时放大以适应contentView.但是,当我粘贴一段文本时,它会将内容的起点和终点垂直放在错误的位置.输入或删除字符会将其重置回正确的位置.

任何想法为什么会这样?

-(void)textViewDidChange:(UITextView *)textView {
    self.textView.frame = CGRectMake(
        self.textView.frame.origin.x,
        self.textView.frame.origin.y,
        self.textView.frame.size.width,
        self.textView.contentSize.height + HEADER_ADDITIONAL_HEIGHT);

    self.textView.contentOffset = CGPointMake(0, 0);

    self.previousContentSize = textView.contentSize;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*son -1

我知道这已经晚了,但我遇到了这个问题,并认为我应该分享我的想法,以防其他人发现自己处于同样的情况。

您走在正确的轨道上,但是textViewDidChange:您错过了一件重要的事情:更新框架高度后设置 contentSize。

// I used 0.f for the height, but you can use another value because according to the docs:
//  "the actual bounding rectangle returned by this method can be larger 
//    than the constraints if additional space is needed to render the entire 
//    string. Typically, the renderer preserves the width constraint and 
//    adjusts the height constraint as needed."
CGSize size = CGSizeMake(textview.frame.size.width, 0.f);
CGRect rect = [string boundingRectWithSize:size
                                   options:OptionsYouNeedIfAny // NSStringDrawingOptions
                                   context:nil];

// Where MinTextViewHeight is the smallest height for a textView that 
//   your design can handle
CGFloat height = MAX(ceilf(rect.size.height), MinTextViewHeight); 
CGRect rect = textView.frame;
rect.size.height = height;
textView.frame = rect;

// Adjusting the textView contentSize after updating the frame height is one of the things you were missing
textView.contentSize = textView.frame.size;
textView.contentOffset = CGPointZero;
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!

有关使用的更多信息,请参阅文档boundingRectWithSize:options:context: