UITextView setContentSize does not work?

721 views Asked by At

I want to change my UITextView's content size, and I tried as below:

[self.textView setContentSize:CGSizeMake(self.textView.contentSize.width, self.textView.contentSize.height+30)];

I found it doesn't work. What's more, I make it in a button's click event to see what will happen.

- (IBAction)click:(id)sender {
    static int y = 0;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, 30, 30)];
    label.text = @"hello";
    y = y+30;
    [self.textView setContentSize:CGSizeMake(self.textView.contentSize.width, self.textView.contentSize.height+30)];
    NSLog(@"%f",self.textView.contentSize.height);
    [self.textView addSubview:label];
}

The result is the setContentSize doesn't work? What's more, contentSize just change for text content changing.

I want to know why, and Is there any method to change the UITextView's contentSize manually?

ADDITION: output for click action

2014-11-17 17:05:56.306 viewControllerAdvance[2371:607] 82.000000 
2014-11-17 17:05:56.455 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.638 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.772 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:56.923 viewControllerAdvance[2371:607] 82.000000
2014-11-17 17:05:57.072 viewControllerAdvance[2371:607] 82.000000
1

There are 1 answers

2
thavasidurai On BEST ANSWER

Try to modify your method like below and check whether it meets your requirement or not.To use below way you need to add your text view on a scroll view and whenever you increase text view's height you suppose to increase scroll view's content size

- (IBAction)click:(id)sender { 

     static int y = 0;
     UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, 30, 30)];
     label.text = @"hello";
     y = y+30;
     [self.textView addSubview:label];

     CGFloat fixedWidth = textView.frame.size.width;
     CGFloat dynamicHeight = textView.frame.size.height+30;

     CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, dynamicHeight)];
     CGRect newFrame = textView.frame;
     newFrame.size = CGSizeMake(fixedWidth, fmaxf(newSize.height, dynamicHeight));
     textView.frame = newFrame;

 }

Also set textview.scrollEnabled = NO;