iOS: 学习笔记, 动态添加按钮

来源:互联网 发布:网络系统安全技术 编辑:程序博客网 时间:2024/05/16 23:42
1. 新建iOS -> Single View Application.

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

////  YYViewController.m//  StudyDynamicButton////  Created by yao_yu on 14-5-27.//  Copyright (c) 2014年 yao_yu. All rights reserved.//#import "YYViewController.h"@interface YYViewController ()@end@implementation YYViewController- (void)onAddButtonClicked{    CGRect pframe = self.view.frame;    CGFloat width = 200;    CGFloat height = 35;    CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/2, pframe.origin.y + height * 2, width, height);    UIButton *btnAddedButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    btnAddedButton.backgroundColor = [UIColor clearColor];    [btnAddedButton setTitle:@"动态添加的按钮" forState:UIControlStateNormal];    btnAddedButton.frame = frame;    [btnAddedButton addTarget:self action:@selector(onDynamicButtonClicked) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btnAddedButton];}-(void) onDynamicButtonClicked{    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您点击了动态按钮" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",@"第二项", nil];    [alert show];}-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{    NSLog(@"按钮索引:%ld", buttonIndex);}- (void)viewDidLoad{    [super viewDidLoad];    //手动添加按钮    CGRect pframe = self.view.frame;    CGFloat width = 200;    CGFloat height = 35;    CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/2, pframe.origin.y + height, width, height);    UIButton *btnAddDynamicButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    btnAddDynamicButton.backgroundColor = [UIColor clearColor];    [btnAddDynamicButton setTitle:@"增加动态按钮" forState:UIControlStateNormal];    btnAddDynamicButton.frame = frame;    [btnAddDynamicButton addTarget:self action:@selector(onAddButtonClicked) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:btnAddDynamicButton];}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

 3. 运行程序.

0 0