Okogeki'sブログ

デキるエンジニアを目指すOkogekiのブログ

TableViewのセルサイズを可変にする。

今回のお題はTableViewのセルサイズを可変にする方法について。

 

TableViewのセルサイズを可変にするには下記コードを加えるのみ

 

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

    UITableViewCell *cell = (UITableViewCell*)[self tableView:self.myTableView cellForRowAtIndexPath:indexPath];

    return cell.frame.size.height;

 

}

 

 

これを行うと、各々のセルサイズを可変にできるので、画面上部に背景画像を表示し、テーブルビューのスワイプに

合わせて背景画像も移動させるなんて事も可能になります。

 

NSArray型のarrayには順に表示したいセルの文を入れてください。

ただし0番目には背景画像として用いているので、0番目のarrayには何も入れないようにしましょう。

 

 

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

    

    static NSString *CellIdentifier = @"Cell";

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    

    if(cell == nil){

        

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        

    }

    

    if(indexPath.row != 0){

        cell.textLabel.text = [NSString stringWithFormat:@"%@",array[indexPath.row]];

        cell.backgroundView = nil;

    }

    

    if(indexPath.row == 0){

        cell.textLabel.text = nil;

        UIImageView *imageView;

        UIImage *image;

        image = [UIImage imageNamed:@"上部に表示したい画像.JPG"];

        imageView = [[UIImageView alloc] initWithImage:image];

        cell.backgroundView = imageView;

        cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, 200);

    }else{

        

        cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, 20);

        cell.textLabel.text = [NSString stringWithFormat:@"%@",array[indexPath.row]];

        cell.backgroundView = nil;

    

    }

    

    return cell;

 

}

 

ちょっとずつですが、Objective-cで作りたいものが作れるようになってきました。