ボタンとイベントの追加メモ
// Java @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Button btn = new Button(this); btn.setText(“ぼたんだよ”); btn.setOnClickListener(new myOnClickListener()); setContentView(btn); } private class myOnClickListener implements OnClickListener{ @Override public void onClick(View v){ ((Button)v).setText(“押されたぞい”); } }
Swift3.x
override func viewDidLoad() { super.viewDidLoad() var btn : UIButton = UIButton() btn.setTitle("ぼたんだよ", for: UIControlState.normal) btn.addTarget(self, action: #selector(ViewController.onClickButton(sender:)), for: UIControlEvents.touchUpInside) self.view.addSubview(btn) } func onClickButton(sender: UIButton) { sender.setTitle("押されたぞい", for: UIControlState.normal) }
Swift2.x
override func viewDidLoad() { super.viewDidLoad(); var btn : UIButton = UIButton(); btn.setTitle("ぼたんだよ", forState: UIControlState.Normal); btn.addTarget(self, action: "onClickButton:", forControlEvents: UIControlEvents.TouchUpInside); self.view.addSubview(btn); } func onClickButton (sender : UIButton){ sender.setTitle("押されたぞい", forState: UIControlState.Normal); }
Swift のほうが長いと思ってたけどそうでもなかった
ついでにObjective-C
// objective-c /* .h */ -(void)onClickButton:(UIButton *) sender; /* .m */ - (void)viewDidLoad { [super viewDidLoad]; UIButton * btn = [[UIButton alloc] init]; [btn setTitle:@"ぼたんだよ" forState: UIControlStateNormal]; [btn addTarget:self action:@selector(onClickButton:) forControlEvents:UIControlStateNormal]; [self.view addSubview:btn]; } - (void)onClickButton:(UIButton *) sender{ [sender setTitle:@"押されたぞい" forState:UIControlStateNormal]; }
ではでは