UITableViewControllerのサブクラスを使用します。この表では、スタイル付きの標準セルを使用していますUITableViewCellStyleDefault
。このスタイルには。が含まれていtextLabel
ます。テキストプロパティにテキストを割り当ててから、テキストの長さ(ポイント単位)が必要になります。
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);
しかし、このコードを実行すると、0.00000の幅が返されます。
text width = 0.000000
Font = '<UICFFont: 0x68b4a90> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 0px'
このテキストの実際の幅を取得するにはどうすればよいですか(通常は表示され、幅が0ではありません)
編集:
コードを含む行を挿入するとif (cell.font){}
、正しいサイズと幅が得られます。
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);
これを表示します:
text width = 98.000000
Font = '<UICFFont: 0x68dc400> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 20px'
ただし、セルのゲッター「フォント」は非推奨です。fontsize / textwidthを取得するための非推奨ではないメソッドはありますか?