xcode 学习笔记2:动态添加view

xcode 学习笔记2:动态添加view  

2011-07-06 16:48:39|  分类: 计算机学习|字号 订阅

前面说的都是用的Interface Builder来编辑.xib文件来给窗口添加各种控件以及给控件绑定数据(IBOutlet)、关联事件响应函数(IBAction)。

这章学习的是动态的添加view,不使用Interface Builder。这里用label和button示例:

 

找到新建工程XXXViewController.m的-(void)loadView方法,去掉注释并添加如下代码

 

- (void)loadView {

//创建一个UIView 对象

UIView *view =

[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];

view.backgroundColor = [UIColor lightGrayColor];

 

//创建一个label view

CGRect frame = CGRectMake(10, 15, 300, 20);

UILabel *label = [[UILabel alloc] initWithFrame:frame];

label.textAlignment = UITextAlignmentCenter;

label.backgroundColor = [UIColor clearColor];

label.font = [UIFont fontWithName:@”Verdana” size:20];

label.text = @”label test”;

label.tag = 1000;

 

//创建一个按钮view

frame = CGRectMake(10, 30, 300, 50);

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

button.frame = frame;

[button setTitle:@”button test” forState:UIControlStateNormal];

button.backgroundColor = [UIColor clearColor];

button.tag = 2000;

 

/*下面这个调用用C++的格式来看就是button->addTarget(this->action, @selector(buttonClicked:), UIControlEventTouchUpInside);

中间的action:以及forControlEvent:实际上都是函数签名的一部分。@selector(buttonClicked:) 相当于函数指针(一个冒号表明函数有一个参数),这里指向的是buttonClicked函数

也就是下面定义的按钮响应函数*/

[button addTarget:self action:@selector(buttonClicked:) forControlEvent:UIControlEventTouchUpInside];

[view addSubview:label];

[view addSubview:button];

self.view = view;

[label release];

}

 

在这个文件中添加按钮响应函数

-(IBAtion) buttonClicked:(id)sender {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Action invoked”

message:@”button clicked”

delegate:self

cancelButtonTitle:”@ok”

otherButtonTitles:nil];

[alert show];

[alert release];

}

 

label的矩形区域是CGRectMake(10, 15, 300, 20); 既左上角坐标是10,15宽度高度分别是300, 20.

button的矩形区域的左上角坐标是10, 30 ,它们有重叠的地方。

这里遮挡是后加到view里面去的遮挡先加进去的。所以button遮挡了label。可以通过

[view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];

来修改遮挡。我的理解是view按照控件加进去的顺给了个index,这个index从0开始递增。显示的时候index数值较大控件遮挡数值较小的。 上面这个函数交换了最先加进去的两个控件(实际上只有这两个)的index

原文地址:https://www.cnblogs.com/moonvan/p/2216301.html