LoginSignup
22
23

More than 5 years have passed since last update.

UIButton NormalとSelectedを交互に切り替えるボタン

Last updated at Posted at 2013-03-11

一回のタップごとに、選択状態と非選択状態を交互に切り替えるボタンです。

[追記] サブクラスでやらなくてもよかったんです。恥ずかしい

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.button addTarget:self action:@selector(buttonDidPush:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)buttonDidPush:(UIButton*)btn
{
    btn.selected = !btn.selected;
}

後はnormal, highlighted, selectedの各画像やタイトルを設定すれば、スイッチ風ボタンの完成です。

コメント欄にてnisin@githubさんにアドバイス頂きました。ありがとうございました!


実装

UIButtonを継承し、UIButtonのselectedとは別に独自に選択と非選択状態を保持します。
- touchesBegan:withEvent:で状態を一時的に変え、UpInsideの場合はその状態を決定させ、UpOutsideやキャンセルの場合は状態を元に戻します。

YSKeepingButton.h
#import <UIKit/UIKit.h>

@interface YSKeepingButton : UIButton

@end
YSKeepingButton.m
#import "YSKeepingButton.h"

@interface YSKeepingButton ()

@property (nonatomic) BOOL keepingButtonSelected;

@end

@implementation YSKeepingButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.selected = !self.keepingButtonSelected;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Cancel");
    self.selected = self.keepingButtonSelected;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    if (CGRectContainsPoint(self.bounds, touchPoint)) {
        // UIControlEventTouchUpInside
        NSLog(@"UpInside");
        self.keepingButtonSelected = !self.keepingButtonSelected;
    } else {
        // UIControlEventTouchUpOutside
        NSLog(@"Cancel UpOutside");
        self.selected = self.keepingButtonSelected;
    }
}

@end

あとは、NormalとSelected状態のイメージやタイトルを設定したり、NormalからSelectedに変わる時だけ- touchesBegan:withEvent:で状態が変化するようにすれば、簡易的ですが押しボタンスイッチの様に動作するボタンが出来ます。

22
23
2

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
22
23