ios - 自动调整 UITableViewCell 大小

标签 ios xcode uitableview

我想知道如何调整表格 View 单元格的大小,并查看所有消息 我的应用程序从服务器上的 xml 获取消息,然后显示它们,但如果消息比文本字段长,它只显示 3 个点 这是我的代码:

 - (NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
return ( messages == nil ) ? 0 : [messages count];
}


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

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

UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"ChatListItem"];
if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChatListItem" owner:self options:nil];
    cell = (UITableViewCell *)[nib objectAtIndex:0];
}

NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
textLabel.text = [itemAtIndex objectForKey:@"text"];
UILabel *stextLabel = (UILabel *)[cell viewWithTag:3];
stextLabel.text = [itemAtIndex objectForKey:@"text"];

UILabel *userLabel = (UILabel *)[cell viewWithTag:2];
userLabel.text = [itemAtIndex objectForKey:@"user"];
UILabel *suserLabel = (UILabel *)[cell viewWithTag:4];
suserLabel.text = [itemAtIndex objectForKey:@"user"];

if ([usernameText.text isEqualToString:userLabel.text]){
    UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat1@2x.png"]];
    [cell setBackgroundView:img];
    [img release];

    textLabel.hidden=NO;
    stextLabel.hidden=YES;

    userLabel.hidden=NO;
    suserLabel.hidden = YES;


}
else{
    UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat2@2x.png"]];
    [cell setBackgroundView:img];
    [img release];

    textLabel.hidden=YES;
    stextLabel.hidden=NO;

    userLabel.hidden=YES;
    suserLabel.hidden = NO;
}

return cell;

}

谢谢

最佳答案

您必须像这样的逻辑一样传递 heightForRowAtIndexPath (尚未准备好代码):

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
NSString *text = [itemAtIndex objectForKey:@"text"];
if(text is larger then what ever you want) {
    return yourSpecificCellHeight;
}
return 37;

要计算文本大小,请参阅 this post on stackOverflow

关于ios - 自动调整 UITableViewCell 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13387445/

相关文章:

ios - codenameone 多播 udp 的 IOS 权利

iOS Safari HTML5 视频覆盖一切

ios - 尝试仅将 NSDate 用于时间

ios - 在范围内找不到类型 'GADInterstitial'?

ios - iOS4 上的 NSFetchedResultsController 问题

ios - XCode 6 和没有 XC 的 Ad-Hoc 分发 : provisioning

ios - 无法删除 UIButtons 和标签。

ios - UITableViewCell Swift 中的自定义 View

ios - 如何向 UITableViewCell 中的 4 个标签添加约束

ios - 我想切换时间洗涤器以 15 分钟为间隔