问题
I'm stuck with some kind of magic: when I try to change UITextView frame (in this case with UISlider), text is drawn in some other (smaller) area than frame (resizing multiple times). The funny thing is that if we slide fast enough when trying to make frame bigger, text is drawn in pretty correct area. Can somebody explain why? I tried to layout, autoresize, set content size and bounds, but nothing works.
- (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
回答1:
Well, after several hours of google, I find out that setting CGRectZero frame before setting my calculated frame value eliminates my problem. (I subclassed UITextView to override setFrame: method). My code bellow.
- (void)setFrame:(CGRect)frame
{
[super setFrame:CGRectZero];
[super setFrame:frame];
}
回答2:
- (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)];
}
来源:https://stackoverflow.com/questions/16301147/why-uitextview-draws-text-in-bad-frame-after-resizing