Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / iPhone-用代码创建界面(Creating Views from Code)

首先新建一个基于视图的项目,名字为ViewTest;在ViewTestViewController.m文件viewDidLoad方法中写上如下代码:
  1. //创建一个视图UIView对象,获取初始化屏幕大小,UIScreen mainScreen该设备的内部屏幕,applicationFrame应用程序的屏幕面积帧点   
  2.     UIView *view =  
  3.     [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];  
  4.       
  5.     //设置背景颜色:灰   
  6.     view.backgroundColor = [UIColor lightGrayColor];  
  7.     //创建标签   
  8.     CGRect frame = CGRectMake(10, 15, 300, 20);//设置标签的位置及大小x y width height表示左上角和大小   
  9.     UILabel *label = [[UILabel alloc] initWithFrame:frame]; //创建并初始化标签,并且使大小是frame   
  10.     label.textAlignment = UITextAlignmentCenter; //标签中文字的对齐方向是居中   
  11.     label.backgroundColor = [UIColor clearColor]; //标签背景颜色透明的   
  12.     label.font = [UIFont fontWithName:@"Verdana" size:20]; //标签文字的Verdana体20号大小   
  13.     label.text = @"This is a label";//标签文字   
  14.     label.tag = 1000;  
  15.     //创建text   
  16.     frame = CGRectMake(10, 70, 300, 30);  
  17.     UITextField *text=[[UITextField alloc]initWithFrame:frame];  
  18.     text.backgroundColor=[UIColor whiteColor];  
  19.     text.text=@"我是任海丽";  
  20.     //创建按钮   
  21.     frame = CGRectMake(10, 120, 300, 50);//按钮位置大小   
  22.     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  23.     button.frame = frame;  
  24.     [button setTitle:@"Click Me, Please!" forState:UIControlStateNormal];  
  25.     button.backgroundColor = [UIColor clearColor];  
  26.     button.tag = 2000;  
  27.     [button addTarget:self  
  28.                action:@selector(buttonClicked:) //响应事件   
  29.      forControlEvents:UIControlEventTouchUpInside];  
  30.     //把标签,文本和按钮添加到view视图里面   
  31.     [view addSubview:label];  
  32.     [view addSubview:button];  
  33.     [view addSubview:text];  
  34.     self.view = view;    
事件响应方法弹出一个警告框:
  1. -(IBAction) buttonClicked: (id) sender{  
  2.     UIAlertView *alert = [[UIAlertView alloc]  
  3.                           initWithTitle:@"Action invoked!" message:@"Button clicked!"  
  4.                           delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  5.     [alert show];  
  6. }  
给出效果图:什么视图界面,你都可以用代码写出来,并设置属性,当然这个不是简便的方法,没有直接拖来的方便,不过这样做是为了熟悉代码并知道是怎么实现的;每个控件都有好多属性,并且要明白是怎么用的。学习过程 中不怕麻烦,希望跟大家一块努力学习!有什么不好的地方,请多指出!!!