我試圖讓單元中的標籤成爲正確的大小,而不管設備或方向如何。我能夠正確地確定行高的大小。我也可以在cellForRowAtIndexPath
中正確設置標籤高度,並可以在我的日誌中檢查。但是,當它達到willDisplayRowAtIndexPath
時,標籤高度已經改變,但只有當單元不是320點寬時。調整UILabel以適應不同寬度的自定義UITableViewCell中的文本
這裏是我的代碼 -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCellIdentifier";
CustomInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[CustomInfoCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
NSArray *objects = [[NSBundle mainBundle] loadNibNamed:@"CustomInfoCell" owner:self options:nil];
cell = objects[0];
}
// Configure the cell...
cell.customTitleLabel.text = [_data[indexPath.row] objectForKey:t];
CGFloat labelWidth = self.view.frame.size.width-40;
NSLog(@"labelWidth:%f",labelWidth);
NSString *text = [_data[indexPath.row] objectForKey:d];//correct text
CGSize labelsize=[text sizeWithFont:cell.customDetailLabel.font constrainedToSize:CGSizeMake(labelWidth, 2000.0) lineBreakMode:cell.customDetailLabel.lineBreakMode];
NSLog(@"labelsize:%f,%f",labelsize.width,labelsize.height);
//For testing
cell.customDetailLabel.backgroundColor = [UIColor redColor];
NSLog(@"Pre: %@",cell.customDetailLabel);
cell.customDetailLabel.frame=CGRectMake(20, 22, labelWidth, labelsize.height);
cell.customDetailLabel.text = text;
NSLog(@"Post: %@",cell.customDetailLabel);
return cell;
}
在willDisplayRowAtIndexPath
我還打印標籤的信息。下面是一行打印 -
2013-03-24 18:33:44.009 Bridge Alert[57793:1e503] labelWidth:728.000000
2013-03-24 18:33:44.010 Bridge Alert[57793:1e503] labelsize:713.000000,76.000000
2013-03-24 18:33:44.010 Bridge Alert[57793:1e503] Pre: <UILabel: 0xad3eaf0; frame = (20 20; 280 21); text = 'Detail'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.011 Bridge Alert[57793:1e503] Post: <UILabel: 0xad3eaf0; frame = (20 22; 728 76); text = 'Detail'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.011 Bridge Alert[57793:1e503] Text set: <UILabel: 0xad3eaf0; frame = (20 22; 728 76); text = 'A bridge is considered 「f...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
2013-03-24 18:33:44.014 Bridge Alert[57793:1e503] Display:<UILabel: 0xad3eaf0; frame = (20 20; 728 190); text = 'A bridge is considered 「f...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x17372eb0>>
正如您所看到的,通過顯示,標籤被調整大小。我假設高度是以某種方式重新計算的,基於單元是否寬320 pt,這是內置在UITableViewCell寬度。
我怎樣才能讓標籤尺寸正確?
您是否嘗試過取消選中自動佈局? – Angelo 2013-03-26 03:45:22
安傑洛,它看起來像你是贏家。將它作爲答案發布,我會仔細檢查它是否適用於所有設備和方向。謝謝。 – James 2013-03-26 11:25:20
很高興我能幫到你。 :) – Angelo 2013-03-26 16:56:43