2014-09-12 5 views
3

Я ноб в Xcode и Objective-C, и мне нужна помощь, чтобы создать динамическую высоту ячейки таблицы представления, о сколько символов в метке. Так будет выглядеть следующим образом: если TextLabel символ более чем 10 он будет изменять размеры listHeight 50 еще, если TextLabel символ более чем 20 он будет изменять размеры listHeight 70 и так далее ...Динамическая пользовательская высота UITableViewCell, основанная на длине текста ярлыка

Этот как я код:

NSLong *text; 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellID = @"ChatTableViewCell"; 
    ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID]; 

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

    Chat * chatObject; 
    chatObject = [chatArray objectAtIndex:indexPath.row]; 
    cell.nameChat.text = chatObject.name; 
    cell.messageChat.text = chatObject.message; 
    cell.messageChat.lineBreakMode = UILineBreakModeTailTruncation; 
    cell.messageChat.numberOfLines = 0; 
    cell.dateChat.text = chatObject.time_entry; 

    //attached foto 
    NSString *setPhoto=chatObject.photo; 
    [cell.imageChat setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/summit/www/media/user/photo/%@",setPhoto]]]]]; 
    cell.imageChat.layer.cornerRadius=cell.imageChat.frame.size.height /2;; 
    cell.imageChat.layer.masksToBounds = YES; 
    cell.imageChat.layer.borderWidth = 0; 
    if (cell.imageChat.image==nil) { 
     cell.imageChat.image=[UIImage imageNamed:@"profile.png"]; 
    } 

    text=[cell.messageChat.text length]; 
    return cell; 
} 

Я пытаюсь это, но не работает:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGFloat height; 
    if(text>=10){ 
     height=100; 
    } 
    else 
     height=70; 
    return height; 
} 

Пожалуйста, помогите мне, я умираю, чтобы сделать это @ _ @ Спасибо заранее

+0

Вы обеспечиваете пример построения ячейки, но это не определяет его высоту. Вы реализовали метод tableView: heightForRowAtIndexPath: '? Что вы пробовали? Кроме того, вы действительно хотите, чтобы высота зависела от количества символов, или вы пытаетесь убедиться, что ячейка достаточно велика, чтобы соответствовать любому содержащемуся в ней тексту? – Jonah

+0

У меня есть метод, но прямо сейчас он содержит только статическое значение return 70; – Edward

+0

Я думаю, вам нужно лучше определить правила, которые, по вашему мнению, будут вычислять правильную высоту ячейки, даже если вы не уверены, как выразить их в коде. В противном случае любой ответ здесь - это всего лишь догадка о том, что вы пытаетесь сделать. Кажется, что ваши ячейки содержат много фрагментов текста, какие из них должны влиять на высоту ячейки? – Jonah

ответ

6

Попробуйте это:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Fetch yourText for this row from your data source.. 
    NSString *yourText = [yourArray objectAtIndex:indexPath.row]; 

    CGSize labelWidth = CGSizeMake(300, CGFLOAT_MAX); // 300 is fixed width of label. You can change this value 
    CGRect textRect = [visitorsPerRegion boundingRectWithSize:labelWidth options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:@"CenturyGothic" size:16.0]} context:nil]; 

    /* Here, you will have to use this requiredSize 
     and based on that, adjust height of your cell. 
     I have added 10 on total required height of 
     label and it will have 5 pixels of padding 
     on top and bottom. You can change this too. */ 

    int calculatedHeight = textRect.size.height+10; 
    return (float)calculatedHeight; 
} 

Надеется, что это работает !!!

+2

sizeWithFont: constrainedToSize: lineBreakMode: амортизируется в iOS 7. Вы должны использовать boundingRectWithSize: options: attributes: context: вместо этого. – rdelmar

+2

ЭТОТ МЕТОД СЛЕДУЕТ УДАЛЯТЬСЯ ПОЖАЛУЙСТА, ИСПОЛЬЗУЙТЕ «БОЛЬШЕ, ЧТОБЫ ПРЯМО» В МЕСТЕ ВЫШЕ – Esha

1

Альтернатива ответам @ Pratik, если вы хотите использовать динамические размеры текста, будет чем-то вроде метода класса в ячейке.

Что мы делаем на работе

+ (CGFloat)cellHeightForTitle:(NSString*)title inTableView:(UITableView*)tableView{ 
    UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; 
    NSString *text = title ?: @"test"; // Just some text 
    CGFloat hotizontalPadding = 0; // account for other content for calculating width of the cell 
    CGFloat desiredWidth = tableView.bounds.size.width - hotizontalPadding; 
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}]; 

    UILabel *label = [[UILabel alloc] init]; 

    label.attributedText = attributedText; 
    label.numberOfLines = 0; 
    label.lineBreakMode = NSLineBreakByWordWrapping; 
    CGSize size = [label sizeThatFits:CGSizeMake(desiredWidth, CGFLOAT_MAX)]; 

    font = nil; 
    attributedText = nil; 

    return size.height; 
} 
Смежные вопросы