iOS学习笔记 4 —— 代码创建界面UIView、UILabel、UITextField、UIButton


[cpp]
  view plain copy

  1.     //创建一个视图UIView对象,获取初始化屏幕大小,UIScreen mainScreen该设备的内部屏幕,applicationFrame应用程序的屏幕面积帧点  
  2.     UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];  
  3.       
  4.     //设置背景颜色:灰  
  5.     view.backgroundColor = [UIColor lightGrayColor];  
  6.     //创建标签  
  7.     CGRect frame = CGRectMake(10, 25, 300, 20);//设置标签的位置及大小x y width height表示左上角和大小  
  8.     UILabel *label = [[UILabel alloc] initWithFrame:frame]; //创建并初始化标签,并且使大小是frame  
  9.     label.textAlignment = NSTextAlignmentCenter; //标签中文字的对齐方向是居中  
  10.     label.backgroundColor = [UIColor clearColor]; //标签背景颜色透明的  
  11.     label.font = [UIFont fontWithName:@"Verdana" size:20]; //标签文字的Verdana体20号大小  
  12.     label.text = @"This is a label";//标签文字  
  13.     label.tag = 1000;  
  14.     //创建text  
  15.     frame = CGRectMake(10, 80, 300, 30);  
  16.     UITextField *text=[[UITextField alloc]initWithFrame:frame];  
  17.     text.backgroundColor=[UIColor whiteColor];  
  18.     text.text=@"This is a TextField";  
  19.     //创建按钮  
  20.     frame = CGRectMake(10, 130, 300, 50);//按钮位置大小  
  21.     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  22.     button.frame = frame;  
  23.     [button setTitle:@"Click Me, Please!" forState:UIControlStateNormal];  
  24.     button.backgroundColor = [UIColor clearColor];  
  25.     button.tag = 2000;  
  26.     [button addTarget:self  
  27.                action:@selector(buttonClicked:) //响应事件  
  28.      forControlEvents:UIControlEventTouchUpInside];  
  29.     //把标签,文本和按钮添加到view视图里面  
  30.     [view addSubview:label];  
  31.     [view addSubview:button];  
  32.     [view addSubview:text];  
  33.     self.view = view;    

事件响应方法弹出一个警告框:

[html]  view plain copy
  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. }  

给出效果图:



什么视图界面,都可以用代码写出来,并设置属性,当然这个不是简便的方法,没有直接拖来的方便,不过这样做是为了熟悉代码并知道是怎么实现的;每个控件都有好多属性,并且要明白是怎么用的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值