ボタンファクトリーを作ってみる(create button factory with objectivec)
こんばんわー、色々なボタンを作るとコードが汚くなるのでボタンファクトリー(factoryClass)を作ってみます。
デザインパターンに精通している訳ではないので、玄人の方は是非アドバイスを下さい。
【 参考 】
ファクトリメソッド(wiki)
iPhoneのUIのスキンをカスタマイズする場合のメモ
ファクトリを用意すると何がよいのか?
・ボタンのUI調整コードをファクトリ内に追いやれる。
・ファクトリー内でボタンを変更するだけで一括で変更が可能。
・少しViewControllerに書くコードが減る。(ただでさえ処理が集まりやすいので)
・別プロジェクトに再利用しやすい。
作るときに既存のUIButtonクラスの構成を参考にボタンタイプ等をEnumで用意しました。
Enumなら変な数値が入るとエラーになるので安心して利用できます。
・プロジェクトテンプレート:SingleViewApplication
・NSObjectのサブクラスでButtonFactoryという名前でクラスを追加
以下ButtonFactoryクラスに記述していきます。
SkinnedButtonFactory.hファイル
#import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, SkinnedButtonType) { SkinnedButtonTypeDefault = 0, // default SkinnedButtonTypeSmallImage // imageDefault }; @interface SkinnedButtonFactory : NSObject + (UIButton *)createButtonWithType:(SkinnedButtonType)buttonType target:(id)target selector:(NSString *)selName imageName:(NSString *)imageName; @end
SkinnedButtonFactory.mファイル(ガーって書いてありますがただボタン作ってreturnしてるだけです。)
#import "SkinnedButtonFactory.h" @implementation SkinnedButtonFactory + (UIButton *)createButtonWithType:(SkinnedButtonType)buttonType target:(id)target selector:(NSString *)selName imageName:(NSString *)imageName { if (buttonType == SkinnedButtonTypeDefault) { UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(0, 0, 44, 44)]; button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; button.contentMode = UIViewContentModeScaleToFill; [button setTitle:@"" forState:UIControlStateNormal]; [button addTarget:target action:NSSelectorFromString(selName) forControlEvents:UIControlEventTouchUpInside]; return button; } if (buttonType == SkinnedButtonTypeSmallImage) { UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)]; button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; button.contentMode = UIViewContentModeScaleToFill; [button addTarget:target action:NSSelectorFromString(selName) forControlEvents:UIControlEventTouchUpInside]; UIImage *img = [UIImage imageNamed:imageName]; [button setImage:img forState:UIControlStateNormal]; return button; } return nil; } @end
ファクトリを使う側(はじめから用意されているViewController)で利用します。
例が微妙ですが、ENUMのSkinnedButtonTypeで違う値を渡すだけで簡単に生成するボタンを切り替える事ができます。
SkinnedButtonTypeSmallImageを渡してimage名を渡せばimageButtonを作成できます。
#import "MyAppViewController.h" #import "SkinnedButtonFactory.h" @interface MyAppViewController () @end @implementation MyAppViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn = [SkinnedButtonFactory createButtonWithType:SkinnedButtonTypeDefault target:self selector:@"pushButton" imageName:nil]; [self.view addSubview:btn]; } - (void)pushButton{ NSLog(@"ボタン押されたよ"); }
もっと色々凝ってみたいんですけど、知識不足かつ
費用対効果のバランスがなかなかわかりません。