我使用Interface Builder創建了一個自定義TableView單元。這是什麼樣子:具有多行UILabel的自定義Tableview單元需要動態高度
對於說明標籤,我需要到自動換行,所以我把它設置爲這樣:
在我SettingsPageViewController,我有下面的表視圖方法被覆蓋:
@implementation SBSettingsViewController
{
NSArray *settingHeaders;
NSArray *settingDescriptions;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupLeftMenuButton];
// Do any additional setup after loading the view from its nib.
settingHeaders = [NSArray arrayWithObjects:@"Label Header 1",@"Label Header 2",nil];
settingDescriptions = [NSArray arrayWithObjects:@"Two line description Two line description Two line description ",@"One Line Description",nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [settingHeaders count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"SettingsTableCell";
SettingsTableViewCell *cell = (SettingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SettingsTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.settingsHeaderLabel.text = [settingHeaders objectAtIndex:indexPath.row];
cell.settingsDescriptionLabel.text = [settingDescriptions objectAtIndex:indexPath.row];
cell.settingsDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.settingsDescriptionLabel.numberOfLines = 0;
CGRect appFrame=[[UIScreen mainScreen] bounds];
cell.settingsDescriptionLabel.preferredMaxLayoutWidth = appFrame.size.width - 15;
[cell.settingsDescriptionLabel sizeToFit];
[cell.settingsDescriptionLabel setNeedsDisplay];
[cell layoutIfNeeded];
return cell;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[tableView setLayoutMargins:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 85;
}
下面是結果頁面的樣子:
正如你可以看到,爲第1的tableview細胞的說明標籤不換行。它只是切斷。 如何讓它包裹?
另外,我想要動態調整Tableview單元格高度。我試圖改變heightForRowAtIndexPath:是UITableViewAutomaticDimension但只是使它看起來超級怪異這樣:
我如何調整與1號線的說明標籤,該行的實現代碼如下高度稍短?
感謝您的幫助!
可能[sizeToFit()的副本返回錯誤的高度 - 需要在heightForRow中查找單元格寬度(http://stackoverflow.com/questions/34731721/sizetofit-returns-wrong-height-need-to-find-cell-width-in -heightforrow) – SwiftArchitect
檢查此鏈接 - http://stackoverflow.com/questions/3472478 3 /如何創建動態視圖在迅速/ 34726428#34726428 –