How to change cell height dynamically in UITableView static cell

廉价感情. 提交于 2020-01-11 05:06:06

问题


I am using UITableViewController instead detailView to show one entity details. I populated one row of data from PFQuery in my viewDidLoad method. I have one cell where I am using label, I want to change the size as per NSString size. I checked a lot of answers but all are related to indexPath which is for dynamic and I have static cells. My label showing complete string, but my cell is fixed. How can I change the height of the cell? Please help me to correct this problem.

Here is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    PFQuery *query = [PFQuery queryWithClassName:@"Entities"];
    [query whereKey:@"name" equalTo:entityName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            PFFile *thumbnail = [objects[0]  objectForKey:@"image"];
            detailsImageView.image = [UIImage imageNamed:@"loader.gif"];
            detailsImageView.file = thumbnail;
            [detailsImageView loadInBackground];
            detailLabel.numberOfLines = 0; // this label need dynamic height and its cell
            detailLabel.text = [objects[0]  objectForKey:@"descriptionLarge"];
            [detailLabel sizeToFit];
        } else {
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            NSLog(@"Error: %@", errorString);
        }
    }];
}

I am trying to do the following by selecting individual cells but it gave me UITableView error as I have not define tableView, how can I define or if you have any other good solution please let me know.

static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

I am also open on criticism of about coding quality so your feedback is valuable for me.


回答1:


If you are using autolayout. Add top, left and right constrain in to your label.

Then in heightForRowAtIndexPath create your cell

static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

Set values to label and calculate size of the label after setting the value

    [cell layoutIfNeeded];
    return cell.label.frame.origin.y+cell.label.frame.size.height;

This will give you the exact hight of the label and your cell height will be same

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
            cell.titleLabel.text=@"YOUR TEXT";
            [cell layoutIfNeeded];
            return cell.titleLabel.frame.origin.y+cell.titleLabel.frame.size.height;
}



回答2:


If it is IOS 8 OR 9, there is a simple fix.

  1. Set up the constrains for the UILabel. (top, left, bottom, right)
  2. Set lines of the UILabel to 0
  3. Add the following code in the viewDidLoad method of the ViewController:
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
  1. override the function:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}



回答3:


Below is how I do.

// this will set height of the row
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   String *yourLongString = "Long text here";
   UILabel *mLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,30)];
                                                                   your size will change here
   mLabel.hidden = YES;
   mLabel.text = yourLongString;
   [mLabel sizeToFit];
           ^^^^^^^^ this is very important

   return mLabel.frame.size.height;
}

Now in cellForRowAtIndexPath adjust the height of actual label as per the height of the cell.

Let me know if you are not clear.




回答4:


I have been doing trying to achieve this from many days but could not. I tried Fahim answer and got clue, following I got from other different answer and have been able to complete it. Code in I added following function to get exact size of my label

-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{

    CGSize maximumSize = CGSizeMake(labelWidth, 10000);
    NSLog(@"crossing getLabelheightForText");

    //provide appropriate font and font size
    CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:@"Trebuchet MS" size:17.0f]
                             constrainedToSize:maximumSize
                                 lineBreakMode:NSLineBreakByTruncatingTail];
    return labelHeighSize.height;
}

Than I have added indexPath with all cell sizes to be returned showing here only one cell size.

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section)
    {
        case 0:
        {
            if (indexPath.row == 0)  // category name size
                return 44.0;   
            if (indexPath.row == 1)  // image size
                return 204;
        }
        default:
            return 44.0       
    }
}

But after this I was getting perfect size of label but still have more to do as I was using PFQuery and tableView indexPath runs first that is why it could not update my table and I was still not able to resize cell. Than here is magic line that reloads my tableView and resolve my issue

[self.tableView reloadData];

Although issue is simple but it has a lot things so I put as reply to help other peoples.



来源:https://stackoverflow.com/questions/25420980/how-to-change-cell-height-dynamically-in-uitableview-static-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!