2014-10-30 6 views
1

привет, я использую UICollectionView, а в UICollectionViewCell мне нужно одно изображение (значок), одно название и некоторое описание. Я новичок в разработке IOS. Я хочу, чтобы высота ячеек UICollectionViewCell зависела от содержимого, потому что может быть название, а изображение будет иметь определенную высоту, но описание имеет разную высоту. может кто-нибудь помочь мне рассчитать высоту описания этикетки. Должен ли я использовать textview для описания?Динамическая высота UICollectionViewCell в зависимости от содержимого

NSDictionary *service1 = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Lorem ipsum dolor sit",@"title", 
       @"Lorem ipsum dolor sit is simply dummy text Lorem ipsum dolor sit is simply dummy text Lorem ipsum dolor sit is simply dummy text Lorem ipsum dolor sit is simply dummy text Lorem ipsum dolor sit is simply dummy text",@"Description", 
       @"image1.png",@"image", 
           nil 
       ]; 
    NSDictionary *service2 = [NSDictionary dictionaryWithObjectsAndKeys: 
       @"Lorem ipsum dolor sit", @"title", 
       @"Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit Lorem ipsum dolor sit",@"Description", 
       @"image2.png",@"image", 
       nil 
           ]; 
dataarray = [[NSMutableArray alloc] initWithObjects:service1, service2, nil]; 


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *identifier = @"Cell"; 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath] ; 
    UIImage * img = [UIImage imageNamed:[[dataarray objectAtIndex:indexPath.row] objectForKey:@"image"]]; 
    UIImageView* iv = [[UIImageView alloc] initWithFrame:CGRectMake(10,10,70,70)]; 
    iv.image = img; 

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 90, 50, 20)]; 

    [titleLabel setText:[[dataarray objectAtIndex:indexPath.row] objectForKey:@"title"]]; 

    titleLabel.textColor = [UIColor blackColor]; 
    titleLabel.font = [UIFont fontWithName:@"Arial" size:8.5]; 
    titleLabel.backgroundColor = [UIColor clearColor]; 
    titleLabel.textAlignment = NSTextAlignmentLeft; 

    [cell addSubview:titleLabel]; 


    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 

    UILabel *desclabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, screenWidth-20, 120)]; 

    [desclabel setText:[[dataarray objectAtIndex:indexPath.row] objectForKey:@"Description"]]; 

    titleLabel.textColor = [UIColor blackColor]; 
    titleLabel.font = [UIFont fontWithName:@"Arial" size:8.5]; 
    titleLabel.backgroundColor = [UIColor clearColor]; 
    titleLabel.textAlignment = NSTextAlignmentLeft; 
    [titleLabel sizeToFit]; 

    [cell addSubview:titleLabel]; 
    [cell addSubview:desclabel]; 
    [cell addSubview:iv]; 

    return cell; 

} 

- (CGSize)collectionView:(UICollectionView *)collectionView 
        layout:(UICollectionViewLayout *)collectionViewLayout 
    sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

    // Adjust cell size for orientation 
    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 
    if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) { 

     return CGSizeMake(screenWidth-10, 170.0f); 
    } 
    return CGSizeMake(screenWidth-10, 190.0f); 
} 
+0

http://stackoverflow.com/questions/14255692/dynamically-resizing-a-uicollectionviewcell – Manthan

+0

@Manthan У меня проблема с текстом описания. как проверить динамическую высоту метки описания? –

+0

: Вместо этого подсчитайте размер текста описания и передайте этот размер напрямую. – Manthan

ответ

1

Хорошо, теперь я вижу. Вам необходимо динамически вычислять многострочную высоту UITextView и увеличивать высоту строки UITableViewCell по умолчанию в соответствии с ней.

Попробуйте использовать что-то вроде этого.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath)path 
{ 
    // take the text value 
    NSString *description = service1[@"title"]; 
    // initial rect value 
    CGRect textFrame = CGRectMake(0,0,cellWidth,10000); // width value is enough for this operation 
    UITextView *myTextView = [[UITextView alloc] initWithFrame:textFrame]; // create textview 
    // set text view attributes as multiline, font, font size etc. 
    myTextView.text = description; 
    CGSize size = [myTextView sizeThatFits:myTextView.frame.size]; // that's all 
    CGFloat height = size.height + someDefaultCellHeight; 
    return height; 
} 

Вы можете создать некоторые частные UITextView элемент в -(void)viewDidLoad способ, чтобы не создавать его каждый раз heightForRow метод делегата вызовов.

+0

мне не нужна коробка с полной шириной. не сетка. –

+1

Почему вы не используете UITableView вместо UICollectionView? С помощью - (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath) метод делегирования пути. – Astoria

+0

хорошо хорошая идея. я попробую сейчас. но может быть, будет снова нужно рассчитать размер описания –

Смежные вопросы