创建新的项目
项目名:
不能以数字开头
不能用中文
简单控件
Label:标签
Button:按钮
Text Field:文本框
头文件
越常用越靠前
枚举都在头文件最上面
其次是协议
最后是类
UIViewController和UIView
UIViewController视图控制器:负责处理UIView响应,负责控制视图展示的数据
以后大部分代码写在UIViewController中
UIView视图:看得见摸得着的,也可以做响应
每个控制器都会有一个跟屏幕一样大的View,这个View我们叫做根视图
所有的UIView都会添加在根视图里面
小飞机案例
#import "ViewController.h"
typedef enum {
TOP = 101,
LEFT = 102,
BOTTOM = 103,
RIGHT = 104
}Direction;
@interface ViewController ()
@end
@implementation ViewController{
UIButton *planeBtn;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
-(void)setupUI{
//背景
UIImageView *view = [[UIImageView alloc] initWithFrame:self.view.bounds];
UIImage *img = [UIImage imageNamed:@"background"];
view.image = img;
[self.view addSubview:view];
//飞机
UIButton *plane = [[UIButton alloc] init];
[plane setImage:[UIImage imageNamed:@"hero1"] forState:UIControlStateNormal];
[plane setImage:[UIImage imageNamed:@"hero2"] forState:UIControlStateHighlighted];
[plane sizeToFit];
plane.center = self.view.center;
[self.view addSubview:plane];
planeBtn = plane;
//按钮
CGFloat offset = 40;//按钮距中心便宜位置
[self createBtn:@"top" :CGPointMake(0, -offset) :TOP];
[self createBtn:@"bottom" :CGPointMake(0, offset) :BOTTOM ];
[self createBtn:@"left" :CGPointMake(-offset, 0) :LEFT ];
[self createBtn:@"right" :CGPointMake(offset, 0) :RIGHT];
}
//创建按钮
-(void)createBtn:(NSString *)name :(CGPoint)offset :(NSInteger)tag{
NSString *normalName = [name stringByAppendingString:@"_normal"];
NSString *highName = [name stringByAppendingString:@"_highlighted"];
UIButton *btn = [[UIButton alloc] init];
CGPoint center = CGPointMake(planeBtn.center.x, planeBtn.center.y + 180);
[btn setImage:[UIImage imageNamed:normalName] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:highName] forState:UIControlStateHighlighted];
btn.frame = CGRectMake(0, 0, 40, 40);
btn.center = center;
btn.tag = tag;
CGRect frame = CGRectOffset(btn.frame, offset.x, offset.y);
btn.frame =frame;
[self.view addSubview:btn];
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
}
//添加点击事件
-(void)click:(UIButton *)sender{
CGRect frame = planeBtn.frame;
switch (sender.tag) {
case TOP:
frame.origin.y -= 20;
break;
case LEFT:
frame.origin.x -= 20;
break;
case BOTTOM:
frame.origin.y += 20;
break;
case RIGHT:
frame.origin.x += 20;
break;
default:
break;
}
planeBtn.frame = frame;
}
@end