I use a subclass of UITableViewController. In this table I use standard-cells with style UITableViewCellStyleDefault
. This style contains a textLabel
. I assign some text to its text-property, and then I need the text's length (in points):
cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
}
cell.textLabel.text = @"some text";
textWidth = [cell.textLabel.text sizeWithFont:cell.textLabel.font].width;
NSLog(@"text width = %f",textWidth);
NSLog(@"Font = '%@'",cell.textLabel.font);
But when I execute this code, it returns a width of 0.00000:
text width = 0.000000
Font = '<UICFFont: 0x68b4a90> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 0px'
What must I do to get the real width of this text (that is normally displayed and who's width is not 0)
Edit:
When I insert a line with the code if (cell.font){}
then I get the correct size and width:
cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
}
cell.textLabel.text = @"some text";
// added line:
if (cell.font){}
textWidth = [cell.textLabel.text sizeWithFont:cell.textLabel.font].width;
NSLog(@"text width = %f",textWidth);
NSLog(@"Font = '%@'",cell.textLabel.font);
displays this:
text width = 98.000000
Font = '<UICFFont: 0x68dc400> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 20px'
But the getter "font" for a cell is deprecated. Is there a non-deprecated method to get the fontsize/textwidth?