xib のモックレイアウト(ボタン)をコード内部処理で変更する
やること
xib で作成したモックのボタンレイアウトを
コードで内部処理して
下を例としたボタンレイアウトに変更する
前提
- ストーリーボードは使わない
- iOS 8.1
登場人物
- CustomButtonsViewController(.xib | .h | .m)
内部処理
.xib
.h
#import <UIKit/UIKit.h> @interface CustomButtonsViewController : UIViewController @end
.m
#import "CustomButtonsViewController.h" @interface CustomButtonsViewController () // アウトレット接続する @property (weak, nonatomic) IBOutlet UIView *viewButton; @end @implementation CustomButtonsViewController #pragma mark - support methods - (UIColor *)createColorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha { return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:alpha]; } #pragma mark - lifecycle methods - (void)viewDidLoad { [super viewDidLoad]; // タイトル文字は 赤 UIColor *titleColor = [self createColorWithRed:255.0 green:0 blue:0 alpha:1.0]; // 背景色は グリーンイエロー UIColor *backgroundColor = [self createColorWithRed:173.0 green:255.0 blue:47.0 alpha:1.0]; // 境界線は 黒 UIColor *borderColor = [self createColorWithRed:0 green:0 blue:0 alpha:1.0]; for(UIView *buttonView in self.viewButton.subviews) { // UIView を UIButton 用にキャストする // http://stackoverflow.com/questions/14056157/changing-the-colour-of-a-uibutton-based-on-its-tag/14056239#14056239 UIButton *button = (UIButton *)buttonView; // 何のアクションも無い時は titleColor の文字色を表示する [button setTitleColor:titleColor forState:UIControlStateNormal]; // 境界線の色を borderColor にする button.layer.borderColor = [borderColor CGColor]; // 境界線の太さを 2 にする button.layer.borderWidth = 2; // ボタンを角丸形式, 丸みを 10 にする button.layer.cornerRadius = 10; // ボタンの背景色を backgroundColor にする [button setBackgroundColor:backgroundColor]; // subview の 親 view (viewButton) 内表示の明示定義 button.clipsToBounds = YES; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end