简体   繁体   中英

iOS - How to calc width of a default textLabel of UITableViewCell?

I tried the code below, but the output is always 0.000000:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellNotification";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    cell.textLabel.text = @"Test Test Test. I am a cell.";

    NSLog(@"%f", cell.textLabel.frame.size.width);

    return cell;
}

How can I know what the width of a default UITableViewCell is? I need this information because I have to set the height for UITableViewCell in

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

The NSLog you are using above is asking for the width of the textLabel within the cell, not the actual cell.

NSLog(@"%f",cell.frame.size.width);

Additionally, if you aren't using the grouped table style, the cells width should return the same as the width of the table.

EDIT: I'm not really sure if this was the question, but if you're asking how to set the width of your cells, you don't have to. This is handled for you.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"%@",NSStringFromCGRect(cell.textLabel.frame));
}

EDIT 2:

Try changing this:

if (cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    cell.textLabel.text = @"Test Test Test. I am a cell.";

To this:

if (cell == nil){
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

cell.textLabel.text = @"Test Test Test. I am a cell.";

The width of the cell will be the width of the table, unless your table is grouped, in which case it is slightly smaller.

However, you probably want the width of whatever label you are using to display the text rather than the cell itself.

A further warning is that the heightForRow... method is called for every row in the table before any cells are created, so you may have to use a known value instead.

我认为您应该在以下位置测试textLabel的宽度:-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM