Skip to content

Instantly share code, notes, and snippets.

@fmtonakai
Created July 9, 2013 08:12
Show Gist options
  • Save fmtonakai/5955591 to your computer and use it in GitHub Desktop.
Save fmtonakai/5955591 to your computer and use it in GitHub Desktop.
accessoryViewにUISwitchを仕掛けたCell
#import <UIKit/UIKit.h>
// delegate method定義
@protocol UITableViewDelegateSwitchCell <UITableViewDelegate>
@optional
-(void)tableView:(UITableView *)tableView didChangeValue:(BOOL)value forRowWithIndexPath:(NSIndexPath *)indexPath;
@end
@interface SwitchCell : UITableViewCell
-(UISwitch *)switchView;
@end
#import "SwitchCell.h"
#import "UITableViewCell+IndexPath.h"
@implementation SwitchCell
{
UISwitch *_switchView;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self setup];
}
return self;
}
-(void)awakeFromNib
{
[self setup];
}
-(void)setup
{
_switchView = [[UISwitch alloc] init];
// 値の変更を受け取る
[_switchView addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
self.accessoryView = _switchView;
}
-(UISwitch *)switchView
{
return _switchView;
}
-(void)valueChanged:(id)sender
{
// tableViewのdelegateに追加したdelegateメソッドを呼び出す
if ([(id <UITableViewDelegateSwitchCell>)self.tableView.delegate respondsToSelector:@selector(tableView:didChangeValue:forRowWithIndexPath:)]) {
[(id <UITableViewDelegateSwitchCell>)self.tableView.delegate tableView:self.tableView
didChangeValue:self.switchView.on
forRowWithIndexPath:self.indexPath];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment