动态添加按钮

1. 新建iOS -> Single View Application.

2. 个性控制器文件YYViewController.m(此处修改为你相应的控制器文件名)

复制代码
 1 //
 2 //  YYViewController.m
 3 //  StudyDynamicButton
 4 //
 5 //  Created by yao_yu on 14-5-27.
 6 //  Copyright (c) 2014年 yao_yu. All rights reserved.
 7 //
 8 
 9 #import "YYViewController.h"
10 
11 @interface YYViewController ()
12 
13 @end
14 
15 
16 @implementation YYViewController
17 
18 - (void)onAddButtonClicked{
19     CGRect pframe = self.view.frame;
20     CGFloat width = 200;
21     CGFloat height = 60;
22     CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/2, pframe.origin.y + height * 2, width, height);
23     UIButton *btnAddedButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
24     btnAddedButton.backgroundColor = [UIColor clearColor];
25     [btnAddedButton setTitle:@"动态添加的按钮" forState:UIControlStateNormal];
26     btnAddedButton.frame = frame;
27     [btnAddedButton addTarget:self action:@selector(onDynamicButtonClicked) forControlEvents:UIControlEventTouchUpInside];
28     [self.view addSubview:btnAddedButton];
29 }
30 
31 -(void) onDynamicButtonClicked{
32     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您点击了动态按钮" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",@"第二项", nil];
33     [alert show];
34 }
35 
36 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
37 {
38     NSLog(@"按钮索引:%ld", buttonIndex);
39 }
40 
41 - (void)viewDidLoad
42 {
43     [super viewDidLoad];
44     
45     //手动添加按钮
46     CGRect pframe = self.view.frame;
47     CGFloat width = 200;
48     CGFloat height = 60;
49     CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/2, pframe.origin.y, width, height);
50     UIButton *btnAddDynamicButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
51     btnAddDynamicButton.backgroundColor = [UIColor clearColor];
52     [btnAddDynamicButton setTitle:@"增加动态按钮" forState:UIControlStateNormal];
53     btnAddDynamicButton.frame = frame;
54     [btnAddDynamicButton addTarget:self action:@selector(onAddButtonClicked) forControlEvents:UIControlEventTouchUpInside];
55     [self.view addSubview:btnAddDynamicButton];
56 }
57 
58 - (void)didReceiveMemoryWarning
59 {
60     [super didReceiveMemoryWarning];
61     // Dispose of any resources that can be recreated.
62 }
63 
64 @end
 
 
posted @ 2015-07-21 12:43  Cheetah_yang  阅读(183)  评论(0编辑  收藏  举报