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

时间:2022-03-08 14:16:08

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 = ;
CGFloat height = ;
CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/, pframe.origin.y + height * , 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 = ;
CGFloat height = ;
CGRect frame = CGRectMake(pframe.origin.x + (pframe.size.width - width)/, pframe.origin.y, 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. 运行程序.