13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

セルをドラッグして状態のON/OFFを切替

Last updated at Posted at 2012-09-02

UITableViewCellの派生クラスに以下のコードを記述します。
ドラッグの検出はUIPanGestureRecognizerを利用しています。

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
		// ドラッグジェスチャー
		UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
		[self addGestureRecognizer:pan];
    }
    return self;
}
// ドラッグジェスチャー処理
- (void)panGesture:(UIPanGestureRecognizer *)sender {
	// ドラッグ開始
    if (sender.state == UIGestureRecognizerStateBegan) {
        _startPt = [sender locationInView:self];
	}
	// ドラッグ移動
	if (sender.state == UIGestureRecognizerStateChanged) {
		CGPoint pt = [sender locationInView:self];
		self.contentView.center = CGPointMake(self.frame.size.width / 2 - (_startPt.x - pt.x), self.contentView.center.y);
	}
	// ドラッグ移動 or ドラッグ終了
	if (sender.state == UIGestureRecognizerStateChanged ||
		sender.state == UIGestureRecognizerStateEnded) {
		
		// ドラッグ移動量 閾値判定
		BOOL changing = (fabs(self.frame.origin.x - self.contentView.frame.origin.x) > 100);
		
		[UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveEaseOut
						 animations:^{
							 // セル位置を元に戻す
							 if (sender.state == UIGestureRecognizerStateEnded) {
								 self.contentView.center = CGPointMake(self.frame.size.width / 2, self.contentView.center.y);
							 }
							 if (changing) {
								 // セル色変更
								 if (! self.task.done) {
									 self.backgroundColor = [UIColor grayColor];
								 } else {
									 self.backgroundColor = [UIColor clearColor];
								 }
								 // 状態を反転
								 if (sender.state == UIGestureRecognizerStateEnded) {
									 self.task.done = ! self.task.done;
								 }
							 } else {
								 // セル色変更
								 if (sender.state == UIGestureRecognizerStateChanged) {
									 if (! self.task.done) {
										 self.backgroundColor = [UIColor clearColor];
									 } else {
										 self.backgroundColor = [UIColor grayColor];
									 }
								 }
							 }
						 } completion:^(BOOL finished) {
						 }];
	}
}
13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?