IOS 开发中 Tableviewcontroller 如何调整高度?

2025-02-24 13:23:03
推荐回答(5个)
回答1:

1、新建一个基于singleview的工程,然后删除默认Storyboard的ViewController,拖拽一个TableviewController,设置为inital Controller


2、往Prototype Cells上拖拽两个UILabel 
如图 


3、为两个Label设置属性 

Title 

设置tag为10 


4、Detail 
设置tag为11 


5、为两个Label设置AutoLayout 

Title 

注意,这里把title放在左上角,Detail放在左下角。然后添加二者之间的距离恒定为1,那么AutoLayout就会自动计算出高度。



新建一个TableviewController,并且讲storyboard上的tableviewController设置为新建的类 

设置Tableview的高度为自动获取


-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension;

}

加入存储数据的数组,并且在初始化里设定数据


@property (strong,nonatomic)NSArray * titleArray;

@property (strong,nonatomic)NSArray * detailArray;

- (void)viewDidLoad {

    [super viewDidLoad];

    self.titleArray = @[@"1",@"2",@"3"];

    self.detailArray = @[@"shot",@"Aduahguhauhguhaudghuahguhudhauhg",@"dhuahgudhaughuahdughuahguhauhguhdahudhuahughduahguhadguhaduhguadhughduahguahguhadugh"];

}

接下来就是Tablview的常用的,很好理解,这里不多赘述


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.titleArray.count;

}

-(BOOL)prefersStatusBarHidden{

    return true;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    UILabel * titleLabel = (UILabel *)[cell viewWithTag:10];

    UILabel * contentLabel = (UILabel *)[cell viewWithTag:11];

    titleLabel.text = self.titleArray[indexPath.row];

    contentLabel.text = self.detailArray[indexPath.row];

    contentLabel.numberOfLines = 0;

    return cell;

}

然后,就得到了我们想要的效果了。

回答2:

如果是StoryBroad的话可以直接在SB文件里设置,如果想用代码修改的话- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

回答3:

UITableViewController默认tableView是全屏的,你可以使用UIViewController,然后自己添加UITableView就好了。

回答4:

修改tableView的frame就可以了,如果用xib的话,把tableView拖成你想要的大小就可以了。

回答5:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

调用这个方法就可