xcode简单教程,实现一个button点击事件

1.新建工程

File->New->Project->SingleViewApplication->Next->ProductName->Next

2.ViewController添加按钮

viewDidLoad 方法添加:

[self setupUI];

实现setupUI:

#pragma mark - Setup
- (void)setupUI {// Hello button.UIButton *helloButton = [UIButton buttonWithType:UIButtonTypeSystem];[helloButton setTitle:@"Hello" forState:UIControlStateNormal];[helloButton addTarget:self action:@selector(onHelloButtonClicked:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:helloButton]; Layout with frame.//[helloButton setFrame:CGRectMake(0, 0, 60, 40)];//helloButton.center = self.view.center; Layout with constraint.helloButton.translatesAutoresizingMaskIntoConstraints = NO; // If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to NO.[self.view addConstraints:@[[NSLayoutConstraint constraintWithItem:helloButton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:60.0],[NSLayoutConstraint constraintWithItem:helloButton attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:40.0],[NSLayoutConstraint constraintWithItem:helloButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0],[NSLayoutConstraint constraintWithItem:helloButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]]];
}

实现点击事件:

#pragma mark - Action
- (void)onHelloButtonClicked:(id)sender {NSLog(@"Hello, world!");UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hello" message:@"Hello, world!" preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {NSLog(@"Cancle Action");}];UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {NSLog(@"OK Action");}];[alertController addAction:cancelAction];[alertController addAction:okAction];[self presentViewController:alertController animated:YES completion:nil];
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部