コードで作成したボタンにイベントを付与, titleLabel を意図的に改行

何がしたいか

  • UIButton をコードで作成し、UIViewController に addSubview で表示する
  • 表示したボタン
    • にイベントを付与する(addTarget で)
    • の titleLabel を意図的に改行させる

f:id:mat5ukawa:20150609231406j:plain

前提

登場人物

  • ButtonsViewController(.xib | .h | .m)

内部処理

xib

f:id:mat5ukawa:20150609230144p:plain

h

#import <UIKit/UIKit.h>

@interface ButtonsViewController : UIViewController
@end

m

#import "ButtonsViewController.h"

@interface ButtonsViewController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@end

@implementation ButtonsViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  // ボタンを作成 / イベント付与 / titleLabel を意図的に改行
  [self createButton];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
}

- (void)createButton
{
  // コードで作成したボタンの
  //   表示位置起点は titleLabel の origin(x, y + 30)   とする
  //   サイズは       (width, height) = (135.0f, 50.0f) とする
  CGRect buttonRect = CGRectMake(self.titleLabel.frame.origin.x,
                                 self.titleLabel.frame.origin.y + 30,
                                 135.0f,
                                 50.0f);
  UIButton *button = [[UIButton alloc] initWithFrame:buttonRect];

  // 白色ボタンにする
  button.backgroundColor = [UIColor whiteColor];
  
  // 黒枠 太さ 0.5f を定義する
  button.layer.borderColor = [[UIColor blackColor] CGColor];
  button.layer.borderWidth = 0.5f;

  // ボタン内の文字(titleLabel)は黒文字にする
  [button setTitleColor:[UIColor blackColor]  forState:UIControlStateNormal];
  button.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:14.0f];
  
  // ボタン内の文字(titleLabel)を途中で改行する
  button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
  [button setTitle:@"plz output log\nthanks" forState:UIControlStateNormal];

  // touchDown した時に touchCustomButton イベントが
  // 実行されるように仕組み作る
  [button addTarget:self action:@selector(touchCustomButton) forControlEvents:UIControlEventTouchDown];

  // ボタンを表示する
  [self.view addSubview:button];
}

-(void)touchCustomButton
{
  NSLog(@"all right. now logged.");
}

@end

「plz output log thanks」Button タップ時のログ

f:id:mat5ukawa:20150609230333p:plain

参考

stackoverflow.com