簡體   English   中英

UITableView-獲取單元格的寬度以適合文本?

[英]UITableView - getting the width of cells to fit text?

我正在編寫一個自定義UITableViewCell對象,並實現了layoutSubviews來在單元格內容更新時調整其大小。

為了實現heightForRowAtIndexPath ,我正在計算自定義UITableViewCell對象中單元格的高度。 我使用NSString sizeWithFont基於UILabel中的文本和UITableView中單元格的寬度來計算單元格的大小。

但是,如何獲取UITableView中單元格的寬度?

現在,我將表格視圖傳遞給對象並使用框架。 但是寬度是整個表格的寬度,而不是單個單元格的寬度。 我在這里想念什么嗎?

提前致謝。

編輯3

我在想,如果真的不可能,只需測試縱向或橫向,然后手動設置寬度即可(ipad僅有兩種不同的方向)。

編輯2

有人對“為什么要用xxxx這樣做”提出了一些疑問。 我知道也許有一種更好的方法來實現自己的目標,即創建一個自定義單元格,該單元格可以根據不同的文本長度來計算其自身的高度。 如果有更好的方法可以做到,我全是:)

編輯

http://img845.imageshack.us/img845/7792/screenshot20121129at193.png

+ (CGFloat)getHeightForCellWithText:(NSString *)text isExpanded:(BOOL)expanded tableView:(UITableViewController *)tv {

ProposalViewCell *cell = [[ProposalViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:@"NormalCell" tableView:tv];

[cell setLabelText:text];

[cell setExpanded:expanded];

[cell layoutSubviews];

return cell.primaryLabel.frame.size.height + cell.readmoreButton.frame.size.height + cell.sendmessageButton.frame.size.height +30;

}


- (void)layoutSubviews {

[super layoutSubviews];

_primaryLabel.numberOfLines = 0; // multiple lines

// size of expanded text label
// sizeWithFont: if text doesn't fit, it is truncated
CGSize expandedSize = [_primaryLabel.text sizeWithFont:myFont constrainedToSize:CGSizeMake(tableView.view.frame.size.width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

// size as expanded by default
_primaryLabel.frame = CGRectMake(10, 10, expandedSize.width, expandedSize.height);

if (expanded==NO) {

    // size of summary text label
    _primaryLabel.numberOfLines = 10;
    CGSize summarySize = [_primaryLabel sizeThatFits:_primaryLabel.frame.size];

    _primaryLabel.frame = CGRectMake(10, 10, summarySize.width, summarySize.height);

}

_readmoreButton.frame = CGRectMake(10, _primaryLabel.frame.size.height+10, 225, 25);

_sendmessageButton.frame = CGRectMake(10, _primaryLabel.frame.size.height+10+_readmoreButton.frame.size.height+10, 225, 25);

}

要獲取單元格的寬度,只需執行此操作...

cell.contentview.frame.size.width

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM