UI07 -UIView视图的基本操作
1、 创建一个工程,在ViewController.h中添加代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化一个矩形变量作为视图显示区域
CGRect rect = CGRectMake(30, 50, 200, 200);
UIView *view = [[UIView alloc] initWithFrame:rect];
[view setBackgroundColor:[UIColor brownColor]];
[self.view addSubview:view];
//创建一个按钮,当点击按钮将动态添加到一个视图
UIButton *btAdd = [[UIButton alloc] initWithFrame:CGRectMake(30, 350, 80, 30)];
[btAdd setBackgroundColor:[UIColor grayColor]];
//设置按钮正常状态下的名字
[btAdd setTitle:@"Add" forState:UIControlStateNormal];
//设置按钮被按下后的名字
[btAdd setTitle:@"down" forState:UIControlStateHighlighted];
//给按钮绑定点击事件,当按下按钮执行添加视图的方法
[btAdd addTarget:self action:@selector(addView) forControlEvents:UIControlEventTouchUpInside];
//将按钮添加到当前视图根视图
[self.view addSubview:btAdd];
//创建第二个按钮,当点击按钮切换根视图中两个视图的层次顺序
UIButton *btBack = [[UIButton alloc] initWithFrame:CGRectMake(120, 350, 80, 30)];
[btBack setBackgroundColor:[UIColor grayColor]];
[btBack setTitle:@"Switch" forState:UIControlStateNormal];
//给按钮绑定点击事件,点击后执行交换视图顺序方法
[btBack addTarget:self action:@selector(bringViewToBack) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btBack];
//创建第三个按钮,点击从当前窗口根视图中删除新添加的视图
UIButton *btReomve = [[UIButton alloc] initWithFrame:CGRectMake(210, 350, 80, 30)];
[btReomve setBackgroundColor:[UIColor grayColor]];
[btReomve setTitle:@"Remove" forState:UIControlStateNormal];
//给按钮绑定点击事件,点击后执行删除操作
[btReomve addTarget:self action:@selector(removeView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btReomve];
}
//创建第一个按钮点后响应的方法
-(void)addView
{
CGRect rect = CGRectMake(60, 90, 200, 200);
UIView *view = [[UIView alloc] initWithFrame:rect];
[view setBackgroundColor:[UIColor purpleColor]];
//给该视图添加标签,以后可通过标签找到该视图
[view setTag:1];
[self.view addSubview:view];
}
//创建第二个按钮的点击事件
-(void)bringViewToBack
{
//通过标签找到新添加的视图
UIView *view = [self.view viewWithTag:1];
//将当前视图移到所有兄弟视图的下方
[self.view sendSubviewToBack:view];
}
//创建第三个按钮的点击事件
-(void)removeView
{
UIView *view = [self.view viewWithTag:1];
//将这个视图删除
[view removeFromSuperview];
}
@end
运行效果: