首页 文章

TableViewCell自动高度

提问于
浏览
0

我在UITableViewCell中有一个标签,我希望我的高度TableViewCell是自动根据标签高度 .

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TWTTweetTableViewCell *cell = (TWTTweetTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TWTTweetTableViewCell" forIndexPath:indexPath]; 

 TWTTweet *tweet = self.tweets[indexPath.row];
cell.tweetMessage.text = tweet.tweetMessage;
cell.timestamp.text = [tweet howLongAgo];

cell.tag = indexPath.row;

TWTUser *user = [[TWTTwitterAPI sharedInstance] userForId:tweet.userId];
cell.user.text = user.username;

return cell;
 

 } 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 165;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //Tapped a tweet
 }

3 回答

  • 3

    用于在viewDidLoad中设置的UITableViewCell的动态高度

    _tableView.estimatedRowHeight = 100.0;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    

    这根据内容高度设置自动单元格高度

    让我知道这个是否奏效...

    https://stackoverflow.com/a/35055320/5085393

    或作为自动尺寸的方法

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
    }
    
     -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    return 100;
    }
    
  • 0

    获得动态更新的高度

    • 加上这些方法

    ===========

    目标C.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewAutomaticDimension;
    }
    
    -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewAutomaticDimension;
    }
    

    ======

    斯威夫特

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
  • 0

    首先转到 storyboard 上的 UITableViewCell 标签的属性检查器,并将 Line Break 属性设置为 Word Wrap . 现在,标签的约束很重要 .

    enter image description here

    仅给出 Top, Bottom, Leading, Trailing 约束,这样单元格可以根据标签的内容调整其高度 .

    然后在您的 viewDidLoad 或您为tableview设置 delegate 的地方添加以下代码,

    self.yourTableView.estimatedRowHeight = 52.0; // Your desired minimum height for the cell.
    self.yourTableView.rowHeight = UITableViewAutomaticDimension;
    

相关问题