iPhone - настроить размер таблицы в соответствии с текстом - PullRequest
1 голос
/ 24 февраля 2011

Есть ли способ настроить размер табличного представления и получить текст для переноса в iPhone?Я использую следующий код, и он успешно регулирует высоту ячейки, но текст не переносится, он просто заканчивается на «....»

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

        City *thisCity = [cities objectAtIndex:indexPath.row];
        NSString * myString = thisCity.cityName;

        cellHeight = [myString sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300.0, 1000.0) lineBreakMode:UILineBreakModeWordWrap];
        return cellHeight.height + 20;
}

Ответы [ 3 ]

1 голос
/ 24 февраля 2011

Здесь есть две вещи:

  1. Обтекание текста в отображаемой метке - для этого вы должны определить для своей UILabel, как он будет выглядеть как контейнер - сколько строк он может иметь, переносит ли он и, конечно, насколько он большой. Вы можете сделать это либо в коде, либо в Интерфейсном Разработчике (в зависимости от того, используете ли вы свою собственную ячейку)

  2. Вы можете изменить ширину вашего UITableView либо в Интерфейсном Разработчике, либо в коде (myTableView.frame = CGRectMake (x, y, width, height)) НО обратите внимание, что если вы используете UITableViewController в качестве контроллера представления - вы НЕ МОЖЕТЕ отрегулировать ширину представления таблицы

1 голос
/ 24 февраля 2011

Нашел идеальный ответ на

Как обернуть текст в UITableViewCell без пользовательской ячейки

Вот код

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


    UITableViewCell *cell =
    [ tv dequeueReusableCellWithIdentifier:@"cell"];
    if( nil == cell ) {

        // this sets up a resusable table cell 
        cell = [ [[UITableViewCell alloc]
                  initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease];

        // support line break mode
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;

        // 0 means any number of lines
        cell.textLabel.numberOfLines = 0;

        // set it up with a consistent font with the height calculation (see below)
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];    

    }


    // set the name of the city 

    if (indexPath.row < cities.count ) {
        City *thisCity = [cities objectAtIndex:indexPath.row];
        cell.textLabel.text = thisCity.cityName;
        } 
        else 
        {

        cell.textLabel.text = @"Add New City...";
        cell.textLabel.textColor = [UIColor lightGrayColor];
        cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }


    return cell;

}

// get the height of the row

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

    City *thisCity = [cities objectAtIndex:indexPath.row];
    NSString * cellText = thisCity.cityName;

    // set a font size
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];

    // get a constraint size - not sure how it works 
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);

    // calculate a label size - takes parameters including the font, a constraint and a specification for line mode
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    // give it a little extra height
    return labelSize.height + 20;

}
0 голосов
/ 24 февраля 2011

Назначьте свою строку в UILabel.и используйте эту тему . в противном случае Присвойте строку UItextView и спрятайте его. Вы можете использовать

 textview.contentSize.height//use this to your cell hieght
...