4

我被某种魔法困住了:当我尝试更改 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;

}

调整大小之前调整大小之前

调整大小后调整大小后

4

2 回答 2

7

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

- (void)setFrame:(CGRect)frame
{
    [super setFrame:CGRectZero];
    [super setFrame:frame];
}
于 2013-05-01T09:08:20.540 回答
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)];

   }
于 2013-04-30T13:37:02.397 回答