为啥 UITextView 高度仅在滚动时变为动态?

Posted

技术标签:

【中文标题】为啥 UITextView 高度仅在滚动时变为动态?【英文标题】:Why UITextView height become dynamic only on scroll?为什么 UITextView 高度仅在滚动时变为动态? 【发布时间】:2015-10-19 13:32:08 【问题描述】:

我在UITableCell 中有一个UITextView,我想根据它的大小使其高度动态化。所以我使用了以下代码。

- (void)textViewDidChange:(UITextView *)textView

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

此代码运行良好,但问题是我的 UITextView 高度只有在我滚动时才会变为动态,否则在加载 UITableView 时它不会变为动态高度。虽然方法被调用了两次。请告诉我为什么会这样?

编辑:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    NSLog(@"cell for row called %d",(int)[arr_post count]);
    //define variables here
    NSMutableAttributedString *mutableAttributeStr;
    NSAttributedString *attributeStr;
    static NSString *CellIdentifier = @"homeCell";
    HomeCell *cell = [self.table_view
                         dequeueReusableCellWithIdentifier:CellIdentifier
                         forIndexPath:indexPath];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];


    //get the post data
    Post *user_post=[arr_post objectAtIndex:indexPath.row];

   //set the button tags
    cell.btn_like.tag=indexPath.row;
    cell.btn_comment.tag=indexPath.row;
    cell.btn_fav.tag=indexPath.row;
    cell.btn_con.tag=indexPath.row;
    cell.btn_book.tag=indexPath.row;

    //add info to buttons
    cell.btn_like.selected=user_post.isPostLiked;
    cell.btn_comment.selected=user_post.isPostCommented;
    cell.btn_fav.selected=user_post.isPostFavourite;
    cell.btn_con.selected=user_post.isPostCondolence;
    cell.btn_book.selected=user_post.isPostBookmarked;
    //add text view path

    //add user info
    cell.label_name.text=user_post.username;
    [cell.img_profile setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.user_profileImage]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];

    //add location
    if([user_post.location isEqualToString:@"Not Available"])
    
        [cell.img_icon_location setHidden:true];
        [cell.label_location setHidden:true];
    
    else
    
        cell.label_location.text=user_post.location;

    
    //ad post info
    cell.tv_post.text=user_post.post_description;
    cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:user_post.modification_date];
    if([user_post.post_image isEqualToString:@"none"] && [user_post.post_video isEqualToString:@"none"])
    

    
    else
    
        UIBezierPath * imgRect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 100, 100)];
        cell.tv_post.textContainer.exclusionPaths = @[imgRect];
        UIImageView *tv_image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 100, 100)];
        [tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];
        [cell.tv_post addSubview:tv_image];

    
    //make textview height dynamic
    cell.tv_post.scrollEnabled=NO;
    [self textViewDidChange:cell.tv_post];


    NSLog(@"textview height is %f",cell.tv_post.frame.size.height);
    NSLog(@"main view height is %f",cell.view_tvContainer.frame.size.height);
    //set the border of uiview
    cell.view_tvContainer.layer.borderColor = [UIColor blackColor].CGColor;
    cell.view_tvContainer.layer.borderWidth = 2.0f;


    //set the like count
    NSString *first_like_user=user_post.recent_like_name;
    int count=(int)[first_like_user length];
    int like_count=[user_post.like_count intValue];

    //chek if tehre are any likes on the post
    NSLog(@"post id is %@",user_post.id);
    NSLog(@"recent like name is %@",user_post.recent_like_name);
    NSLog(@"like count is %d",like_count);

    if(like_count>0)
    
        NSLog(@"inside like count block");
        cell.label_like_count.lineBreakMode=NSLineBreakByWordWrapping;
        [cell.label_like_count sizeToFit];
        [cell.label_like_count setHidden:false];
        NSString *str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count-1];
         if(like_count==1)
        
            if([myUsername isEqualToString:first_like_user])
            
                first_like_user=@"You asjlike sdfsdfsd sfd ";
                count=3;

            
            else
            
                first_like_user=[first_like_user stringByAppendingString:@" like this post"];


            

        
        else if(like_count==2)
        
            first_like_user=[first_like_user stringByAppendingString:@" and "];
            str_like_count=[str_like_count stringByAppendingString:@" other like this post"];
            first_like_user=[first_like_user stringByAppendingString:str_like_count];

        
        else
        
            if(like_count>1000)
            
                like_count=like_count/1000;
                str_like_count=[NSString stringWithFormat:@"%lu",(unsigned long)like_count];
                str_like_count=[str_like_count stringByAppendingString:@"k"];
                first_like_user=[first_like_user stringByAppendingString:@" and "];
                str_like_count=[str_like_count stringByAppendingString:@" others like this post"];
                first_like_user=[first_like_user stringByAppendingString:str_like_count];
            
            else
            
                first_like_user=[first_like_user stringByAppendingString:@" and "];
                str_like_count=[str_like_count stringByAppendingString:@" others like this post"];
                first_like_user=[first_like_user stringByAppendingString:str_like_count];

            


        
        mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];

        attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]];

        [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
        [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];

        [mutableAttributeStr appendAttributedString:attributeStr];

        [cell.label_like_count setAttributedText:mutableAttributeStr];
    
    else
    
        NSLog(@"not inside like count");
        [cell.label_like_count setHidden:true];


    


   // show dynamic comment
    NSMutableArray *user_comments=user_post.comments;
    float comment_count=[user_post.comment_count intValue];
    NSLog(@"post id is %@",user_post.id);
    NSLog(@"arr comments count is %lu",(unsigned long)comment_count);
    NSLog(@"arr user comments count is %lu",[user_comments count]);
    if(comment_count>0)
    
        NSLog(@"post id is %@",user_post.id);

        //make label multiline
        cell.first_comment.lineBreakMode=NSLineBreakByWordWrapping;
        [cell.first_comment sizeToFit];
        cell.second_cmment.lineBreakMode=NSLineBreakByWordWrapping;
        [cell.second_cmment sizeToFit];
        cell.third_comment.lineBreakMode=NSLineBreakByWordWrapping;
        [cell.third_comment sizeToFit];

        NSMutableAttributedString *mutableAttributeStr;
        NSAttributedString *attributeStr;
        if(comment_count==1)
        
            [cell.first_comment setHidden:false];
            [cell.second_cmment setHidden:true];
            [cell.third_comment setHidden:true];

        
        else if(comment_count==2)
        
            [cell.first_comment setHidden:false];
            [cell.second_cmment setHidden:false];
            [cell.third_comment setHidden:true];

        
        else
        
            [cell.first_comment setHidden:false];
            [cell.second_cmment setHidden:false];
            [cell.third_comment setHidden:false];
            [cell.btn_more_comments setHidden:false];

        
        for(l=0;l<[user_comments count];l++)
        
            NSLog(@"inside loop %d",l);
            Comment *comment=[user_comments objectAtIndex:l];
            NSLog(@"comment is %@",comment.comment);
            NSLog(@"comment user is %@",comment.user_name);
            if(l==0)
            
                NSLog(@"l is zero");
                NSString *comment_string=[comment.user_name stringByAppendingString:@" "];
                comment_string=[comment_string stringByAppendingString:comment.comment];
                int count=(int)[comment.user_name length];
                mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
                NSLog(@"comment string is %@",comment_string);
                attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]];

                [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
                [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];

                [mutableAttributeStr appendAttributedString:attributeStr];
                [cell.first_comment setAttributedText:mutableAttributeStr];


            
            else if(l==1)
            
                 NSLog(@"l is 1");
                NSString *comment_string=[comment.user_name stringByAppendingString:@" "];
                comment_string=[comment_string stringByAppendingString:comment.comment];
                int count=(int)[comment.user_name length];
                mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];

                attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]];

                [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
                [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];
                NSLog(@"comment string is %@",comment_string);
                [mutableAttributeStr appendAttributedString:attributeStr];
                [cell.second_cmment setAttributedText:mutableAttributeStr];
            
            else if(l==2)
            
                 NSLog(@"l is 2");
                NSString *comment_string=[comment.user_name stringByAppendingString:@" "];
                comment_string=[comment_string stringByAppendingString:comment.comment];
                int count=(int)[comment.user_name length];
                mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];

                attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]];

                [mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0]  range:NSMakeRange(0, count)];
                [mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:@"#48a0dd"] range:NSMakeRange(0, count)];

                [mutableAttributeStr appendAttributedString:attributeStr];
                [cell.third_comment setAttributedText:mutableAttributeStr];

            
        
    
    else
    
        [cell.first_comment setHidden:true];
        [cell.second_cmment setHidden:true];
        [cell.third_comment setHidden:true];
        [cell.btn_more_comments removeFromSuperview];

    
    cell.label_time.text=[BaseController getTimestampForDate:date];
    [arr_indexpath addObject:indexPath];
    return cell;


【问题讨论】:

为 rowatIndexpath 方法显示您的单元格 heightForRowAtIndexPath 方法中有什么? 请检查我的更新代码 天哪,你的方法太大了。我在寻找文本视图时迷路了。 对不起,我只有这个 【参考方案1】:

试试这个。

-(void)dynamicTextSize
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(200, 300, 200, 30)];
textView.center = self.view.center;
[self.view addSubview:textView];

NSString *string  = @"You long text here";
textView.text = string;

//UIFont *font = [UIFont fontWithName:@"Arial" size:16.0f];
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:textView.font, NSFontAttributeName, nil];

textView.backgroundColor = [UIColor lightGrayColor];

CGRect frame  = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, 10000) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil];

CGRect mFrame = textView.frame;
mFrame.size.width = frame.size.width;
mFrame.size.height = frame.size.height;
textView.frame = mFrame;

//NSLog(@"frame2:%@",NSStringFromCGRect(textView.frame));

【讨论】:

我可以改变 textview 的高度,但为什么这只发生在滚动上?【参考方案2】:

尝试致电[cell layoutIfNeeded];并将self.table_view替换为tabelview。这可能会解决您的问题

【讨论】:

以上是关于为啥 UITextView 高度仅在滚动时变为动态?的主要内容,如果未能解决你的问题,请参考以下文章

动态 UITableViewCell 高度内的动态 UITextView?

如何仅在 UITextView 上强制水平滚动

如何动态调整 UITextView 的高度

xcode 6无法滚动长的uitextview

UITableView动态单元格高度仅在某些滚动后才能正确显示

滚动视图中的 UITextView 与 Autolayout iOS 不工作