Autoexpand UITextView height dynamically in ios

后端 未结 4 1022
醉话见心
醉话见心 2021-01-17 00:03

I have a simple textView who\'s data gets populated dynamically. I want to resize the height of the textview once the data is populated so that I don\'t see a vertical scrol

相关标签:
4条回答
  • 2021-01-17 00:39

    You can try it by sizeToFit method of UITextview.

    [myTextView sizeToFit];
    
    0 讨论(0)
  • 2021-01-17 00:49

    You can do something like:

    tViewhobbies=[[UITextView alloc]init];
        tViewhobbies.backgroundColor=[UIColor clearColor];
        [tViewhobbies setText:@"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."];
        CGSize maxSize = CGSizeMake(300.0f, CGFLOAT_MAX);
        CGSize requiredSize = [tViewhobbies sizeThatFits:maxSize];
        tViewhobbies.frame = CGRectMake(10,330, requiredSize.width, requiredSize.height);
        tViewhobbies.layer.cornerRadius=5;
        [tViewhobbies setUserInteractionEnabled:NO];
        tViewhobbies.font=[UIFont systemFontOfSize:16.0];
        tViewhobbies.backgroundColor=[UIColor colorWithRed:0.662745 green:0.662745 blue:0.662745 alpha:0.5];
        tViewhobbies.delegate=self;
        tViewhobbies.scrollEnabled=NO;
        [scrollView addSubview:tViewhobbies];
        [tViewhobbies sizeToFit];
    

    First you have to assign the text before setting its frame for calculating its frame and than you can do sizeToFit. I am sure it'll work. And all below labels or textviews' y position should be relative to that textview.

    0 讨论(0)
  • 2021-01-17 00:52

    This depends on font size. Following code retrieve the font size of text and return the height and width required. This may help you to create the logic:

    NSDictionary *attribs1 = @{
                              NSFontAttributeName: tViewhobbies.font
                              };
    
    CGSize textViewSize = [tViewhobbies.text sizeWithAttributes:attribs1];
    
    0 讨论(0)
  • 2021-01-17 00:57

    Below is the trick I always use...

    1. Create one fake UITextView
    2. Put data into it
    3. Call sizeToFit
    4. Hide this textview
    5. Set actual textview height based on this fake uitextview...

    Done....

    0 讨论(0)
提交回复
热议问题