上文中是在沒有storyboard下創建UI,但是那樣的方法既繁瑣,又不符合MVC設計模式。
所以本文通過IB初始化界面,然後通過代碼動態添加UILabel和刪除UILabel
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) NSMutableArray *labels;
@end
@implementation ViewController {
NSInteger _nextY;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor grayColor]];
//初始化labels數組
self.labels = [NSMutableArray array];
//獲取主視圖的寬度
CGRect rect = [self.view bounds];
CGFloat width = rect.size.width;
//添加按鈕設置在視圖寬度1/3處
UIButton *addButton = [[UIButton alloc] initWithFrame:
CGRectMake(width/3 - 20, 50, 40, 20)];
[addButton setTitle:@"添加" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:addButton];
//刪除按鈕設置在視圖寬度2/3處
UIButton *removeButton = [[UIButton alloc] initWithFrame:
CGRectMake(2 * width/3 - 20, 50, 40, 20)];
[removeButton setTitle:@"刪除" forState:UIControlStateNormal];
[removeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:removeButton];
_nextY = 100;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)add:(id)sender {
CGRect rect = [self.view bounds];
CGFloat width = rect.size.width;
//創建一個UILable控件
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(width/2 - 80, _nextY, 160, 30)];
label.text = [NSString stringWithFormat:@"nextY = %ld", (long)_nextY];
[self.labels addObject:label];
[self.view addSubview:label];
_nextY += 50; //控制nextY的值加50
}
- (IBAction)remove:(id)sender {
NSLog(@"remove");
NSLog(@"%lu",(unsigned long)[self.labels count]);
if ([self.labels count] > 0) {
//將最後一個labels刪除
[[self.labels lastObject] removeFromSuperview];
[self.labels removeLastObject];
_nextY -= 50;
}
}
@end