状態切替ボタン、UISwitchのような機能

1426 ワード

作成ボタン
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.frame = CGRectMake(10.0, 10.0, 100.0, 40.0);
	[button setTitle:@"Normal" forState:UIControlStateNormal];
	UIImage *image = [UIImage imageNamed:@"normal.png"];
	UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
	[button setBackgroundImage:newImage forState:UIControlStateNormal];
	button.adjustsImageWhenHighlighted = NO;
	[button addTarget:self action:@selector(buttonSwitch:) forControlEvents:UIControlEventTouchDown];
	[self.view addSubview:button];

イベント処理
-(void)buttonSwitch:(id)sender
{
	static BOOL isHighlighted = NO;
	
	UIButton *button = (UIButton*)sender;
	UIImage *image = nil;
	NSString *title = nil;
	if (isHighlighted)
	{
		title = @"Normal";
		image = [UIImage imageNamed:@"normal.png"];
	}
	else
	{
		title = @"Hightlight";
		image = [UIImage imageNamed:@"highlight.png"];
	}
	
	[button setTitle:title forState:UIControlStateNormal];
	UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
	[button setBackgroundImage:newImage forState:UIControlStateNormal];
	isHighlighted = !isHighlighted;
}