其实也不能算原创哈,照着《疯狂ios讲义》来的。
我的Xcode更新到了6.1,新建工程ios里面已经没有Empty Application了,很多书却都是从这里开始的。这个例子是建立了Single View Application,但是不修改默认的Main.storyboard设计文件,直接在程序代码中创建整个UI界面,程序只使用该界面文件中的UIView作为容器。以下是修改ViewController.m文件,整个工程只需要修改这个文件。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSMutableArray* labels;
@end
@implementation ViewController
int nextY = 80;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor grayColor];
self.labels = [NSMutableArray array];
UIButton* addButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
addButton.frame = CGRectMake(30, 30, 60, 40);
[addButton setTitle:@"添加" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
UIButton* removebutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
removebutton.frame = CGRectMake(230, 30, 60, 40);
[removebutton setTitle:@"删除" forState:UIControlStateNormal];
[removebutton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:addButton];
[self.view addSubview:removebutton];
}
- (void)add:(id)sender{
UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(80, nextY, 160, 30)];
label.text = @"亚特兰蒂斯";
label.textColor = [UIColor blueColor];
[self.labels addObject:label];
[self.view addSubview:label];
nextY += 50;
}
- (void)remove:(id)sender{
if ([self.labels count] > 0) {
[[self.labels lastObject] removeFromSuperview];
[self.labels removeLastObject];
nextY -= 50;
}
}
/*
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
*/
@end