xyk blog

最近は iOS 開発の記事が多めです。

スクロール画面で固定されたビューを実現するには

環境:iOS Deployment Target 7.1

スクロールする画面上でも固定されてスクロールしない View を実装する方法。

UIScrollViewDelegate プロトコルを実装して、スクロールする度に呼ばれるscrollViewDidScroll:で scrollView.contentOffset プロパティの座標を取得して固定したいビューの座標に設定してあげればよい。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    _fixedView.frame = CGRectMake(100 + scrollView.contentOffset.x,
                                  300 + scrollView.contentOffset.y,
                                  100,
                                  100);
}

こんな感じ。

f:id:xyk:20140930140234g:plain

サンプルコード

FixedViewController.h

#import <UIKit/UIKit.h>

@interface FixedViewController : UIViewController
<
UITableViewDelegate,
UITableViewDataSource,
UIScrollViewDelegate
>
@end

FixedViewController.m

#import "FixedViewController.h"

@interface FixedViewController ()

@end

@implementation FixedViewController
{
    UITableView *_tableView;
    NSMutableArray *_items;
    UIView *_fixedView; // 固定するビュー
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _tableView = [[UITableView alloc] initWithFrame:[self.view bounds]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

    // テストデータ
    _items = [NSMutableArray array];
    for (int i = 0; i < 100; i++) {
        NSString *item = [NSString stringWithFormat:@"item %d", i];
        [_items addObject:item];
    }

    // 固定するビューの作成
    _fixedView = [[UIView alloc] initWithFrame:CGRectMake(100, 300, 100, 100)];
    _fixedView.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.5];
    [_tableView addSubview:_fixedView];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 固定するビューの座標を設定
    _fixedView.frame = CGRectMake(100 + scrollView.contentOffset.x,
                                  300 + scrollView.contentOffset.y,
                                  100,
                                  100);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = _items[indexPath.row];
    if (indexPath.row % 2 == 0) {
        cell.backgroundColor = [UIColor whiteColor];
    } else {
        cell.backgroundColor = [UIColor lightGrayColor];
    }
    return cell;
}

@end