有没有这样的方法或解决方案可以根据内容自动调整tableview的行高。我的意思是我不想指定行高,而是要根据行的内容来指定行高。如果没有这样的方法,那么告诉我当设备的方向改变时如何改变高度的解决方案?
6 回答
您必须找到内容的高度并可以使用它
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return "your content height + your padding height value";
}
在方向更改时,只需重新加载您的表格视图即可;
看一下这个
// --dynamic cell height according to the text--
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = <your text>;
CGSize constraint = CGSizeMake(210, 20000.0f);
CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Helvetica-Light" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// constratins the size of the table row according to the text
CGFloat height = MAX(size.height,60);
return height + (15);
// return the height of the particular row in the table view
}
希望这可以帮助
编辑方向你试过这个方法吗?
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
或者,如果您的表格单元格是使用标签和图像视图等自定义的,那么您可以在每个单元格上使用 setAutoresizingMask: 来自动调整方向。
[yourview setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
您可以实施
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
UITableView 的委托方法。
如果你谷歌它,你应该能够找到很多关于它的教程。
这是一个例子:
http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/
你必须使用:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
是的 - 我知道你非常了解这种方法,我已经仔细阅读了你的问题。
- 您必须使用该委托方法来动态控制行的高度。我的建议是检查来自 tableview 后端数据模型的每个单元格的内容,并返回一个适合该单元格的数字,例如:
NSDictionary *thisCell = (NSDictionary *)[myArray objectAtIndexPath:indexPath.row];
NSString *myCellContents = [thisCell valueForKey:@"MyStringIWantToCheckOut"];
if ([mycellContents length] > 25) {
return 80;
} else {
return 40;
}
至于方向发生变化时,您必须在委托方法中执行此操作:
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
然后reloadData
开火TableView
。
- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row){
case 0:
if(indexPath.section == 0)
//title
return 75;
default:
return 75;
}
}
func tableView(_ heightForRowAttableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension }
for dynamic height for row otherwise you can give static height instead of "UITableViewAutomaticDimension"