UIButton にリサイズした画像を埋め込む
後述の「課題」が残った方法である事、ご承知下さい
やること
- left_arrow.png(130x46 x1) を (50x50 x1) へ等比率画像に変換する
- 変換画像をボタン(200x200) に埋め込む
前提
登場人物
- CustomButtonsViewController(.xib | .h | .m)
- left_arrow.png(130x46 x1)
内部処理
xib
全体
left_arrow(UIImageView)
- Size Inspector で 50x50 へ設定
- Attributes Inspector の「Mode」で「Aspect Fit」 を設定
h
#import <UIKit/UIKit.h> @interface CustomButtonsViewController : UIViewController @end
m
#import "CustomButtonsViewController.h" @interface CustomButtonsViewController () // アウトレット接続する @property (weak, nonatomic) IBOutlet UIView *viewButtons; @property (strong, nonatomic) IBOutlet UIImageView *imageViewLeftArrow; @end @implementation CustomButtonsViewController #pragma mark - support methods // parentFrame の中点に childFrame の中点が合致する rect を返すメソッド - (CGRect)rectChildPlaceToParentCenter:(CGRect)parentFrame childFrame:(CGRect)childFrame { return CGRectMake((parentFrame.size.width - childFrame.size.width) / 2, (parentFrame.size.height - childFrame.size.height) / 2, childFrame.size.width, childFrame.size.height); } #pragma mark - lifecycle methods - (void)viewDidLoad { [super viewDidLoad]; // mainButton(UIButton) のインスタンスを取得 UIButton *mainButton = self.viewButtons.subviews[0]; // ボタンに埋め込む矢印画像 (UIButton@UIImageView#frame) // の位置をボタンの中央に位置づける self.imageViewLeftArrow.frame = [self rectChildPlaceToParentCenter:mainButton.frame childFrame:self.imageViewLeftArrow.frame];; // leftArrow の view を mainButton の view へ埋め込む [mainButton addSubview:self.imageViewLeftArrow]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // view が dealloc される直前に // mainButton の view から leftArrow の view を remove する // 方法によっては viewDidDisappear にて実施 [self.imageViewLeftArrow removeFromSuperview]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - event methods // ボタン内 (画像埋め込み領域、非画像領域(オレンジ)どちらでも) // をクリックすると // Log に "touched main Button" が表示される - (IBAction)touchedMainButton:(UIButton *)sender { NSLog(@"touched main Button"); } @end
課題
- ボタンをタップしても、画像はハイライト(暗くなったり明るくなったり) しない
- addsubview で view を埋め込んでいるだけなので
(UIButton@UIViewImage の setFrame を弄っても frame の値が動いてくれぬ)