Обтекание текста в UITableView в iOS - PullRequest
4 голосов
/ 05 ноября 2011

Я хочу обернуть текст ячеек в UITableView.Я использую следующий код, но выравнивание ячеек происходит неправильно, как динамически изменить высоту ячейки?Я заметил, что в делегате tableView есть встроенный метод - (CGFloat) cellHeightForRow, но я могу динамически принимать текст и устанавливать высоту, поскольку в данных JSON есть текст переменной длины

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";  

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
    if (cell == nil) {  
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];  
    }  
    [cell.textLabel sizeToFit];
    cell = [[[UITableViewCell alloc]
             initWithStyle: UITableViewCellStyleSubtitle
             reuseIdentifier: @"UITableViewCell"] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

    NSDictionary *person = [myPeople objectAtIndex:[indexPath row]]; 

    NSString *name = [person valueForKey:@"name"];
    cell.detailTextLabel.text = [person valueForKey:@"time"];
    return cell; 
}

Это то, что я пробовал до сих пор:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSDictionary *person = [myPeople objectAtIndex:[indexPath row]]; 
    NSString *cellText    =[person valueForKey:@"text"];
    UIFont *cellFont      = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize      = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    int buffer  = 10;
    return labelSize.height + buffer;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";  

    UITableViewCell *cell = [commentView dequeueReusableCellWithIdentifier:CellIdentifier];  
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.textLabel.numberOfLines = 6;
        cell.textLabel.font          = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];
        [cell.textLabel setMinimumFontSize:13.0];
        [cell.textLabel setAdjustsFontSizeToFitWidth:NO];
    } 

    NSDictionary *person = [myPeople objectAtIndex:[indexPath row]]; 

    NSString *personName = [person valueForKey:@"text"];
        cell.textLabel.text = personName;
   // cell.detailTextLabel.text = [person valueForKey:@"date"];

    return cell; 
}

Тем не менее вывод выглядит слишком комковатым и плотным

Ответы [ 2 ]

15 голосов
/ 05 ноября 2011

Внутри вашего cellForRowAtIndexPath: функция.В первый раз, когда вы создаете свою ячейку:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) 
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font          = [UIFont fontWithName:@"HelveticaNeue" size:21.0];
}

Вы заметите, что я также установил количество строк для метки равным 0. Это позволяет использовать столько строк, сколько необходимо.

Вам также нужно указать, насколько большим будет ваш UITableViewCell, так что в вашей функции heightForRowAtIndexPath:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText    = @"some text which is part of cell display";
    UIFont *cellFont      = [UIFont fontWithName:@"HelveticaNeue" size:21.0];    
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize      = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    int buffer  = 10;
    return labelSize.height + buffer;
}

Я добавил дополнительный 10 к моей возвращенной высоте ячейки, потому что мне нравитсянебольшой буфер вокруг моего текста.

ОБНОВЛЕНИЕ: Если выходные данные выглядят слишком туго и комковато, сделайте это -

[cell.textLabel setMinimumFontSize:13.0];
[cell.textLabel setAdjustsFontSizeToFitWidth:NO];

Это должно решить вашу проблему.

0 голосов
/ 05 ноября 2011

Чтобы изменить высоту вашей ячейки, вам нужно изменить ее кадр в cellForRowAtInexPath и убедиться, что метка имеет правильные флаги автоматического определения размера.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...