Change UITableviews height to fit its content in xcode?

血红的双手。 提交于 2020-01-15 23:38:31

问题


I need to make UITaableView to fit its content.I m loading array data in UITableView.But when I fixed some static size ,eventhough the items are less it is showing the extra space.So I need to make dynamic height to UITableView but could not achieve it ..

autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 140, 200, self.autocompleteTableView.contentSize.height) style:UITableViewStyleGrouped];
        autocompleteTableView.delegate = self;
        autocompleteTableView.dataSource = self;
        autocompleteTableView.scrollEnabled = YES;
       [self.view addSubview:autocompleteTableView];

When I write this I could not see the TableView itself..How can I get it ?


回答1:


For dynamic tableview height. You need to apply dynamic frame.

For ex,

myTable.frame = CGRectMake(x,y,w,[row count] * 44);

Where 44 is default size of tableview cell

Thus, you need to know each cell height, In order to apply this.

Enjoy Programming




回答2:


You try the following code

CGRect tblFrame = [tableView frame];
[tableView setFrame:CGRectMake(tblFrame.origin.x, 
                                tblFrame.origin.y, 
                                tblFrame.size.width, 
                                tblFrame.size.height + 20)];



回答3:


Call this method before creating a table view in view did Load. It calculates the Height of the content and and returns total height of table view

-(NSInteger)calculateheightOfText{

    for (int i=0; i<[yourarray count]; i++) {
        NSString *cellText =[yourarray objectAtIndex:i];
        UIFont *cellFont = [UIFont fontWithName:@"ArialMT" size:17.0];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

        heightOfTableview = heightOfTableview+labelSize.height + 20;
    }
    heightOfTableview = heightOfTableview +([items count]*35);

    return heightOfTableview;
}



回答4:


First you can get your content(text) height and then according to this height you can adjust your tableView frame.

CGSize size = [@"Your string" 
               sizeWithFont:[UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:22] 
               constrainedToSize:CGSizeMake(320, CGFLOAT_MAX)];


来源:https://stackoverflow.com/questions/13448426/change-uitableviews-height-to-fit-its-content-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!