我使用使用自定義的UITableViewCell子類,NoteCell
表視圖。子類有兩個文本標籤,一個名稱標籤和一個日期標籤,它們並排放置在單元格中。我的目標是讓名稱標籤自行調整,以便無論如何顯示完整日期。如何動態調整UITableViewCell中兩個文本標籤寬度的大小?
中的cellForRowAtIndexPath,我試圖計算和設定的兩個文本視圖的寬度,這樣的日期得到充分的展示和名字標籤被截斷。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"NoteCell";
NoteCell *cell = (NoteCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
cell.dateLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
cell.nameLabel.text = @"A name that should be truncated";
cell.dateLabel.text = @"A long date to use as an example";
// Set the widths
// First calculate how wide the date label needs to be.
cell.dateLabel.text = @"A really long date";
CGSize dateLabelSize = [cell.dateLabel.text sizeWithFont:cell.dateLabel.font];
CGFloat dateExpansionAmount = fabsf(dateLabelSize.width - cell.dateLabel.frame.size.width) + 10.0f;
cell.dateLabel.frame = CGRectMake(cell.dateLabel.frame.origin.x - dateExpansionAmount,
cell.dateLabel.frame.origin.y,
dateLabelSize.width,
cell.dateLabel.frame.size.height);
CGFloat nameLabelWidth = cell.dateLabel.frame.origin.x - cell.nameLabel.frame.origin.x;
cell.nameLabel.frame = CGRectMake(cell.nameLabel.frame.origin.x,
cell.nameLabel.frame.origin.y,
nameLabelWidth,
cell.nameLabel.frame.size.height);
}
不幸的是,因爲我不認爲我設置/正確計算幀邊界做的結果是不正確的。看到下面的圖片。
忽視的問題與框架計算是否有更好的方式來處理這個問題,或者是手動定位文本標籤框架的唯一途徑?
您是否已嘗試在被問到的標籤上設置autoResize屬性? – 2012-02-24 23:33:55
你的意思是說,設置autoresize屬性,即支柱和彈簧? - 如果是這樣,那麼當設備旋轉時,將調整標籤的大小以擴大或縮小。 – 2012-02-24 23:40:33
您正確設置了日期標籤的調整大小掩碼,但未設置名稱標籤。它應該具有靈活的寬度和固定的右邊距。 – sosborn 2012-02-25 00:37:31