为什么UITextView在调整大小后在坏帧中绘制文本?

时间:2013-04-30 13:29:37

标签: ios xcode uitextview uislider cgrect

我坚持使用某种魔法:当我尝试更改UITextView框架(在本例中使用UISlider)时,文本将绘制在除框架之外的其他(较小)区域中(多次调整大小)。有趣的是,如果我们在尝试使框架更大时滑动得足够快,则会在非常正确的区域绘制文本。有人可以解释一下原因吗?我尝试布局,自动调整大小,设置内容大小和范围,但没有任何作用。

- (void)viewDidLoad
{
    [super viewDidLoad];

    _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
    _textView.backgroundColor = [UIColor greenColor];
    _textView.text = @"some useless text which will be drawn bad";
    [self.view addSubview:_textView];

    UISlider *slide = [[UISlider alloc] initWithFrame:CGRectMake(10, 130, 100, 20)];
    [slide setValue:0.0];
    [slide addTarget:self action:@selector(changedValue:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:slide];
}
- (void)changedValue:(UISlider *)slider
{
    CGRect textViewFrame = _textView.frame;
    textViewFrame.size.width = [slider value] * 200;
    _textView.frame = textViewFrame;

}

调整大小Before resize

之前 调整After resize后的

2 个答案:

答案 0 :(得分:7)

好吧,经过几个小时的谷歌,我发现在设置我的计算帧值之前设置CGRectZero帧消除了我的问题。 (我将UITextView子类化为覆盖setFrame:方法)。我的代码吼叫。

- (void)setFrame:(CGRect)frame
{
    [super setFrame:CGRectZero];
    [super setFrame:frame];
}

答案 1 :(得分:0)

- (void)viewDidLoad
  {
      [super viewDidLoad];

     _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
     _textView.backgroundColor = [UIColor greenColor];
     [_textView setTextAlignment:NSTextAlignmentCenter];
     _textView.text = @"some useless text which will be drawn bad";
     [self.view addSubview:_textView];

      UISlider *slide = [[UISlider alloc] initWithFrame:CGRectMake(10, 130, 100, 20)];
      [slide setMinimumValue:100.0];
      [slide setMaximumValue:200.0];
      [slide addTarget:self action:@selector(changedValue:) forControlEvents:UIControlEventValueChanged];
      [self.view addSubview:slide];
  }

 - (void)changedValue:(UISlider *)slider
  {
      NSLog(@"slider.value = %f",[slider value]);

      CGSize textSize=[_textView.text sizeWithFont:[UIFont systemFontOfSize:18]
                                 constrainedToSize:CGSizeMake([slider value], 100)
                                     lineBreakMode:NSLineBreakByWordWrapping];

     [self.textView setFrame:CGRectMake(self.textView.frame.origin.x, self.textView.frame.origin.y, textSize.width, textSize.height)];

   }