Men的博客

欢迎光临!

0%

什么是KVC?
// Key Value Coding的简写, 称为键值编码
// 作用: 访问对象中属性的一种方式, 通过字符串为关键字访问属性

KVC的基本使用
// 问题: setValue:forUndefinedKey:

KeyPath的使用

// 4.常用方法
// setValuesForKeysWithDictionary:

//总结: 开发中常用
//1. setValuesForKeysWithDictionary方法
//2. 当对象没有对应属性出现错误怎么解决

//KVC常用用途把网络上字典转化为model
NSDictionary *dict = @{@”speed”:@(100),@”temp”:@”test”};
for(NSString *key in dict)
{
[car setValue:dict[key] forKey:key];
}

//设置car中engine对象的power属性
[car setValue:@(100) forKeyPath:@”engine.power”];

//把字典中各个属性的值赋给对象对应的属性或实例变量
[car setValuesForKeysWithDictionary:dict2];

什么是KVO

// Key Value Observing的简写, 键值监听
// 作用: 需要监视一个属性的变化, 变化了之后做出处理

KVO的基本使用

// 常用
// 项目监听一个属性的变化, 并在界面上显示, 使用KVO
// 实例: 监听和显示下载进度
//KVO
//效果: 当speed有了变化之后执行self中observeValueForKeyPath方法
[car addObserver:self forKeyPath:@”speed” options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
监听的实现
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
double newSpeed = [[object valueForKeyPath:keyPath] doubleValue];

NSLog(@”newSpeed = %f”,newSpeed);
}
程序完成的时候要移除监听
-(void)dealloc
{
//移除监听
//[car removeObserver:self forKeyPath:@”speed”];
}

KVC 与 KVO 是 Objective C 的关键概念,个人认为必须理解的东西,下面是实例讲解。
Key-Value Coding (KVC)
KVC,即是指 NSKeyValueCoding,一个非正式的 Protocol,提供一种机制来间接访问对象的属性。KVO 就是基于 KVC 实现的关键技术之一。
一个对象拥有某些属性。比如说,一个 Person 对象有一个 name 和一个 address 属性。以 KVC 说法,Person 对象分别有一个 value 对应他的 name 和 address 的 key。 key 只是一个字符串,它对应的值可以是任意类型的对象。从最基础的层次上看,KVC 有两个方法:一个是设置 key 的值,另一个是获取 key 的值。如下面的例子:

KVO这种编码方式使用起来很简单,很适用与datamodel修改后,引发的UIVIew的变化这种情况,就像上边的例子那样,当更改属性的值后,监听对象会立即得到通知。

什么是GCD

Grand Central Dispach–
好用:1.简单
基于block c函数接口
功能强大:支持多核心编程
支持高级编程功能

创建和使用

dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

创建和使用

//开启一个新的线程
//queue
//三种:main——queue主线程队列
//globle——queue全局队列。异步任务加载这里
//自定义的
dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
for (int i=0; i<100; i++)
{
NSLog(@”A=%d”,i);
}
});
dispatch_async(queue, ^{
for (int i=0; i<100; i++)
{
NSLog(@”B=%d”,i);
}
});

模拟网络数据下载

[self simulaterNetworkDataDownload];

延迟执行,延时5s执行

[self delayRunCode];

有的代码指向执行一次

[self runOneCode];
[self runOneCode];
[self runOneCode];
[self runOneCode];

多个任务同时执行,等待所有任务结束

// 模拟迅雷多路下载后关机
[self simulaterThreadDownload];

}
-(void)simulaterThreadDownload
{
dispatch_group_t group=dispatch_group_create();

//任务添加
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i=0; i<30; i++)
{
NSLog(@” B=%d”,i);
[NSThread sleepForTimeInterval:0.1];
}
});
//先是所有任务执行完成
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@”所有的任务执行完成”);
});
}
-(void)runOneCode
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@”这句话我只说一次”);
});
}
-(void)delayRunCode
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@”我是一只小小小小鸟,永远永远也飞不高”);
});

}
-(void)simulaterNetworkDataDownload
{
_progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 20)];
[self.view addSubview:_progressView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i=0; i<100; i++)
{
注意:不要再主线程里更新UI
// _progressView.progress+=0.01;

dispatch_async(dispatch_get_main_queue(), ^{
_progressView.progress+=0.01;
});
[NSThread sleepForTimeInterval:0.1];
}
NSLog(@”下载完成”);
});

}

创建播放器对象

NSString *path=[[NSBundle mainBundle]pathForResource:@”lalala.mp3” ofType:nil];
_player =[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
//预加准备
[_player prepareToPlay];

//添加一个按钮:开始播放
[self.view addSystemButtonWithFrame:CGRectMake(100, 100, 100, 30) title:@”播放” action:^(UIButton *button) {
[_player play];
}];

//添加一个按钮:停止播放
[self.view addSystemButtonWithFrame:CGRectMake(100, 150, 100, 30) title:@”暂停” action:^(UIButton *button) {
[_player pause];
}];
//滑块控件
_slider=[[UISlider alloc]initWithFrame:CGRectMake(100, 200, 100, 30)];
[self.view addSubview:_slider];
[_slider addTarget:self action:@selector(dealSlider:) forControlEvents:UIControlEventValueChanged];
_slider.value=1;
进度条
_progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(50, 50, 200, 20)];
[self.view addSubview:_progressView];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(dealTimer:) userInfo:nil repeats:YES];

}

-(void)dealTimer:(NSTimer *)t
{
_progressView.progress=_player.currentTime / _player.duration;
}
-(void)dealSlider:(UISlider *)s
{
_player.volume=s.value;
}

网络音乐的播放

1.使用AudioStreamer.h开源库
配置开源库
创建对象
{
AudioStreamer *_streamer;
}

NSString *urlString=@”http://music.baidu.com/data/music/file?link=http://yinyueshiting.baidu.com/data2/music/134378654/2191061104400128.mp3?xcode=ffd5ff02dfd6ef1a480aa81e262460cd6e2eede49a06f7cb&song_id=2191061";
// 如果是self调用时的警告可以
// __weak UIViewController *vc=self;

__block typeof (_streamer) t=_streamer;

[self.view addSystemButtonWithFrame:CGRectMake(100, 100, 100, 30) title:@”播放” action:^(UIButton *button) {
t =[[AudioStreamer alloc]initWithURL:[NSURL URLWithString:urlString]];
[t start];
}];

播放本地视频文件

//1、配置
//添加mediaPlayer
//如何播放在线视频文件

#import “ViewController.h”

#import <MediaPlayer/MediaPlayer.h>

#import “UIView+ZJQuickControl.h”

  • (void)viewDidLoad
    {
    [super viewDidLoad];

[self.view addSystemButtonWithFrame:CGRectMake(100, 100, 100, 30) title:@”播放” action:^(UIButton *button) {

NSString *path=[[NSBundle mainBundle]pathForResource:@”dzs.mp4” ofType:nil];
MPMoviePlayerViewController *mpvc=[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:path]];
[self presentViewController:mpvc animated:YES completion:nil];
}];

播放在线视频

//http://quiet.local/baoman.mp4

[self.view addSystemButtonWithFrame:CGRectMake(100, 100, 100, 30) title:@”播放网络mp4” action:^(UIButton *button) {

NSString *path=@”http://quiet.local/baoman.mp4";
MPMoviePlayerViewController *mpvc=[[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:path]];
[self presentViewController:mpvc animated:YES completion:nil];
}];

NSOperation、NSOperationQueue

//对于NSThread的封装,提供了更为方便的使用接口
//支持block

创建和使用

//最好不要直接使用===一般继承自己的类,然后再使用
//
//NSOperation *operation1=[[NSOperation alloc] init];
// 使用NSBlockOperation /NSInvocationOperation
NSBlockOperation *bo=[NSBlockOperation blockOperationWithBlock:^{
for (int i=0; i<100; i++)
{
NSLog(@”A=%d”,i);
[NSThread sleepForTimeInterval:0.1];
}
}];
//启动
// [bo start];
NSBlockOperation *bo2=[NSBlockOperation blockOperationWithBlock:^{
for (int i=0; i<100; i++)
{
NSLog(@”A=%d”,i);
[NSThread sleepForTimeInterval:0.1];
}
}];
//启动
// [bo2 start];
//操作队列 理解为:线程池
//注意:如果直接执行NSBlockOperation的花会在主线程中执行
//如果加到NSOperationQueue就会新开1个线程执行
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
[queue addOperation:bo];
[queue addOperation:bo2];

}

什么是NSThread?

NSThread 是ios提供的操作和使用线程的一个类
线程:
进程:理解,活着的程序,是程序执行的一个操作系统实体

NSThread的创建线程

//每个线程执行对应一个方法
NSThread *thread1=[[NSThread alloc]initWithTarget:self selector:@selector(thread1:) object:nil];
//启动线程
[thread1 start];

//以类方法创建线程
// [NSThread detachNewThreadSelector:@selector(dealThread2:) toTarget:self withObject:nil];
//可以实现同时执行的效果,以前都是先执行A后执行B,现在有了多线程,可以实现同时执行

为什么要实行线程

//UI界面中如果直接执行耗时任务的,界面会卡死,为了能让界面执行耗时任务的时候继续反应,使用新的线程去执行耗时任务
//应用场合:下载网络文件,同时执行多个任务,加载大文件,加载大数据
//3.为什么要实行线程
UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
button.frame=CGRectMake(100, 100, 100, 30);
[button setTitle:@”耗时任务” forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
-(void)btnClick:(UIButton *)button
{
//暂停5秒
// [NSThread sleepForTimeInterval:5];
// [self dealThread2:nil];
// 如果直接执行的话UI界面会卡死,没有反应
//开启一个新的线程执行
[NSThread detachNewThreadSelector:@selector(dealThread2:) toTarget:self withObject:nil];

}

//4.监控线程的执行完成
//如何知道那个线程执行接收,使用block–以后要学
//4.监控线程的执行完成
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealThreadExit:) name:NSThreadWillExitNotification object:nil];
-(void)dealThreadExit:(NSNotification *)no
{
NSLog(@”线程执行完成”);
NSLog(@”ui=%@”,no.userInfo);
}
//5.线程的控制,线程同步
//遇到情况:多个线程访问同一块数据
//如何解决:
//a+10 1.先从内存拿出,修改,再放回去
//访问数据的时候加锁
//5.线程的控制,线程同步
_lock=[[NSLock alloc]init];

[NSThread detachNewThreadSelector:@selector(addFunc:) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(subFunc) toTarget:self withObject:nil];

[self setAddBlock:^(NSString *mmm){
NSLog(@”hbbbgeregour====%@”,mmm);
}];

#pragma mark - 线程同步
-(void)addFunc:(NSThread *)th
{
for(int i=0;i<1000;i++)
{
//加锁
[_lock lock];
_num++;
[NSThread sleepForTimeInterval:0.001];
//减锁
[_lock unlock];

}
NSLog(@"add num=%d",_num);
if (self.addBlock)
{
    self.addBlock(@"add");
}

}
-(void)subFunc
{
for(int i=0;i<1000;i++)
{
//加锁
// [_lock lock];
_num–;
[NSThread sleepForTimeInterval:0.001];
//减锁
// [_lock unlock];

}
NSLog(@"sub num=%d",_num);

}

//6.UI主线程如何操作UI?
//ui主线程,
// 工作子线程
// 注意:不要在子线程中直接操作UI,交给主线程UI;
[self howToUpDateUIInSubThread];
-(void)howToUpDateUIInSubThread
{
_progress =[[UIProgressView alloc]initWithFrame:CGRectMake(10, 200, 300, 20)];
[self.view addSubview:_progress];
//添加一个按钮
UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
button.frame=CGRectMake(100, 300, 100, 30);
[button setTitle:@”下载文件” forState:UIControlStateNormal];
[self.view addSubview:button];
[button addTarget:self action:@selector(startDownloadClick:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)startDownloadClick:(UIButton *)button
{
[NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:nil];
}
-(void)download:(NSThread )thread
{
for(int i=0;i<1000;i++)
{
//更新UI
// _progress.progress+=0.01;
//在主线程中执行一个方法
[self performSelectorOnMainThread:@selector(upDateUI) withObject:nil waitUntilDone:NO];
[NSThread sleepForTimeInterval:0.001];
NSLog(@”进度为%f%%”,_progress.progress
100);
}
}
-(void)upDateUI
{
_progress.progress+=0.001;
}

我们为什么要实现单元格的复用机制

单元格每一个cell的生成都是要init alloc的,所以当我们滑动表格试图的时候会生成很多cell,无异于浪费了大量的内存
单元格的复用机制原理
一开始的时候我们创建了桌面最多能显示的单元格数,cell
当我们向下滚动表格试图的时候,单元格上部的内容会消失,下部的内容会出现,这个时候我们将上部分消失的单元格赋给下部分出现的单元格
因此我们就做到了只生成了屏幕范围可显示的单元格个数,就实现滑动表格试图时,以后不会再init alloc单元格cell了,从而实现了节省内存的原理
单元格的复用机制
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

定义一个cell标示符,用以区分不同的cell
以后有不同风格的cell就可以使用了
static NSString *cellID=@”cell”;
从cell复用池中拿到可用的cell
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
检测,拿到一个可用的cell
if(cell ==nil)
{
创建新的cell
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}

<3>显示分组数据
显示每段 多少section数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return _dataArray.count;
}
告诉表格每段要显示多少行
重要参数:section每次传入制定序号
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *array=_dataArray[section];
return array.count;
}

单元格行的高度

//通过这个方法可以指定任意行的高度。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 44.0f;
}

单元格的背景
单元格的内容视图contentView

某行选中的事件处理

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{}
//某行被取消选中了
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@”被取消选中了”);
}

添加头部视图和尾部视图

// 添加头部试图
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
imageView.image=[UIImage imageNamed:@”fenjing.jpg”];
_tableView.tableHeaderView=imageView;
// 添加尾部试图
UIImageView *footImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 150)];
footImage.image=[UIImage imageNamed:@”head2.jpg”];
_tableView.tableFooterView=footImage;

表格视图的编辑(难点)

<1>单元格的删除操作[重点, 必须掌握]

<2>单元格的增加操作

<3>单元格的移动操作

<4>多行选中和多行删除操作

2.表格视图的设置

<1>设置表格的索引

<2>设置段头和段尾

<3>表格的分割线

3.表格视图的搜索

<1>添加搜索条 UISearchBar–>tableHeaderView

4.表格视图控制器

cell的定制

1.我们使用MVC模式实现cell的定制。
什么是MVC模式
V是:VIew视图 作用:展示数据,接收用户交互
C是:Controller控制器
作用:负责把数据从Model中拿出来放到View上。
根据View的操作区修改数据。
M是:Model模型 作用:存储和表示数据

理解:简单理解为每个界面分为三层——Model,VIew,Controller
效果:让开发变得更简单,可维护性更强,可扩展性更强,可阅读性更强
下面我们就具体看一下MVC模式应该怎么设计,在MVC模式下如何定制cell
1.Model的设计
这里:你要建立数据模型,存储数据(数据模型:就是oc中的类)
现在获取的数据本质上是原始数据,
以后原始数据有很多中 plist JSON 数据库 文本文件
注意:不要直接使用原始数据
把所有的原始数据存储到数据模型Model
将解析数据存储到Model中
建立数组接收每个Model对象。

2.cell的定制
就是将cell上所有的空间全部封装成一个类。
在这个类里,我们创建这些控件,设置相应的坐标
将这些类添加到self.contentView

属性

内容区域contentSize
@property(nonatomic) CGSize contentSize;
偏移量contentOffset
@property(nonatomic) CGPoint contentOffset;
弹簧效果bounces
@property(nonatomic) BOOL bounces;
分页效果pagingEnabled
@property(nonatomic,getter=isPagingEnabled) BOOL pagingEnabled;
允许滑动视图本身,如果设为no只能通过方法滑动,不能直接用手滑动
@property(nonatomic,getter=isScrollEnabled) BOOL scrollEnabled;
显示水平进度条showsHorizontalScrollIndicator
@property(nonatomic) BOOL showsHorizontalScrollIndicator;
显示垂直进度条showsVerticalScrollIndicator
@property(nonatomic) BOOL showsVerticalScrollIndicator;
放大和缩小的倍数
@property(nonatomic) CGFloat minimumZoomScale;
@property(nonatomic) CGFloat maximumZoomScale;

1缩放到某个区域,(具体出现的区域受缩放倍数的影响)

  • (void)zoomToRect:(CGRect)rect animated:(BOOL)animated;

2种通过代码滑动视图的方法,一个是设置偏移量,一个是滑动到某个区域(常用第一个)

  • (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;
  • (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated;

滚动视图的基本使用

演示UIScrollView滚动试图基本使用
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 11000, 5600)];
imageView.image=[UIImage imageNamed:@”1001.jpg”];
[self.view addSubview:imageView];
使用滚动试图
声明一个滚动试图
UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:scrollView];
imageView放到了滚动试图中
[scrollView addSubview:imageView];
滚动试图比较特殊,有两个大小。本身大小,其中内容大小
scrollView.contentSize=CGSizeMake(11000, 5600);
滚动试图常用属性
是否显示水平或竖直滚动条。
水平,横向
scrollView.showsHorizontalScrollIndicator=NO;
竖直,纵向
scrollView.showsVerticalScrollIndicator=NO;
设置分页滚动
scrollView.pagingEnabled=YES;
设置是否可以拉出空白区域,bounces蹦跳 scrollView.bounces=YES;

滚动视图的基本原理 + 滚动视图的事件处理

滚动试图缩放和基本原理UIScrollViewDelegate
scrollView.delegate=self;
开始拖拽
滚动。。。。。
结束拖拽
开始减速
滚动。。。。。
减速结束(滚动停止);
【UIScrollViewDelegate】
代理方法
滑动过程中

  • (void)scrollViewDidScroll:(UIScrollView *)scrollView;
    开始拖动
  • (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
    停止拖动
  • (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
    开始滑动
  • (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView;
    停止滑动
  • (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;

滚动视图的缩放

设置最大最小缩放比例
通过代理方法,告诉滚动试图,哪个试图应该缩放
scrollView.maximumZoomScale=10;
scrollView.minimumZoomScale=0.1;
代理方法,告诉scrollView哪个试图应该缩放
当试图滚动的时候执行
试图缩放。
允许缩放的视图(一个scrollview中只能有一个可以缩放且必须设置可以缩放的范围)
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
返回被缩放的试图
return imageView;
}

轻击手势Tap

UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dealTap:)];
[_imageView addGestureRecognizer:tap];

}
-(void)dealTap:(UITapGestureRecognizer *)tap
{
NSLog(@”被点击了”);
}

缩放手势Pinch

UIPinchGestureRecognizer *pain=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(dealPinch:)];
[_imageView addGestureRecognizer:pain];
}
-(void)dealPinch:(UIPinchGestureRecognizer *)pinch
{
有一个非常重要的控件 ,缩放系数。pinch.scale
NSLog(@”缩放”);
仿射变换(改变view的位置大小)
_imageView.transform=CGAffineTransformMakeScale(pinch.scale, pinch.scale);
}

旋转手势Rotation

UIRotationGestureRecognizer *rotation=[[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(dealrotation:)];
[_imageView addGestureRecognizer:rotation];

}
-(void)dealrotation:(UIRotationGestureRecognizer *)ro
{
重要属性。。rotation.rotation表示旋转角度
_imageView.transform=CGAffineTransformMakeRotation(ro.rotation);
}

滑动手势Swipe

UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(dealSwipe:)];
[_imageView addGestureRecognizer:swipe];
}
-(void)dealSwipe:(UISwipeGestureRecognizer *)swipe
{
NSLog(@”滑动”);
注意:滑动默认的方向是向右
swipe.direction=UISwipeGestureRecognizerDirectionRight;
static int index=0;
NSArray *array=@[@”1173.jpg”,@”1092.jpg”];
index++;
if(index>array.count-1)
{
index=0;
}
_imageView.image=[UIImage imageNamed:array[index]];
// if(index ==0)
// {
// _imageView.image=[UIImage imageNamed:@”1173.jpg”];
// index=1;
// }
// else
// {
// _imageView.image=[UIImage imageNamed:@”1092.jpg”];
// index=0;
// }
}

拖移手势Pan

UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(dealPan:)];
[_imageView addGestureRecognizer:pan];
}
-(void)dealPan:(UIPanGestureRecognizer *)pan
{
重要的属性locationInView
CGPoint point=[pan locationInView:self.view];
_imageView.center=point;
}
长按手势LongPress
UILongPressGestureRecognizer *longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(dealLongPress:)];
[_imageView addGestureRecognizer:longPress];

}
-(void)dealLongPress:(UILongPressGestureRecognizer *)longPress
{
NSLog(@”长按”);
重要的属性 longPress.state
if(longPress.state==UIGestureRecognizerStateBegan)
{
UIAlertView *al=[[UIAlertView alloc]init];
al.message=@”是否保存图片”;
[al addButtonWithTitle:@”取消”];
[al show];
}

}

1.UISwitch 开关控件
2.UIActivityIndicatorView 活动提示视图
3.UISlider 滑块控件
4.UISegmentedControl 分段选择
5.UIStepper 计数器/步进器
6.UIProgrecessView 进度条
7.UITextView 文本视图
8.UIActionSheet 动作列表
9.UIAlertView 警告视图
10. 扩展知识

UISwitch 开关控件

创建显示
UISwitch *mySwich=[[UISwitch alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
[self.view addSubview:mySwich];
注意:宽度和高度对控件没有影响。
控件的大小是固定的 width是51;higth是31;
属性;
状态是真还是假 一开始启动时的状态。
mySwich.on=YES;
设置关状态下的颜色
mySwich.tintColor=[UIColor redColor];
设置开状态下的颜色
mySwich.onTintColor=[UIColor blueColor];
设置圆点的颜色
mySwich.thumbTintColor=[UIColor yellowColor];
事件处理
细节:事件类型—ValueChanged
[mySwich addTarget:self action:@selector(dealSwith:) forControlEvents:UIControlEventValueChanged];
UIActivityIndicatorView 活动提示视图

需求:在网路下载中,提示用户正在下载中 ,那么我们就可以使用活动指示器。
self.view.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
创建添加
UIActivityIndicatorView *aiv=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
UIActivityIndicatorViewStyleWhiteLarge,白的大号的
UIActivityIndicatorViewStyleWhite,白的正常号的
UIActivityIndicatorViewStyleGray,灰的。
[self.view addSubview:aiv];
只有中心,没有大小
aiv.center=CGPointMake(160, 200);
注意:要有开始动画
[aiv startAnimating];
设置颜色
aiv.color=[UIColor purpleColor];
模拟5s之后下载完成
5s后执行方法dealTimerout:
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(dealTimerout:) userInfo:aiv repeats:NO];
}
-(void)dealTimerout:(NSTimer *)timer
{
UIActivityIndicatorView *aiv=timer.userInfo;
[aiv stopAnimating];
}
UISlider 滑块控件

创建
UISlider *slider=[[UISlider alloc]initWithFrame:CGRectMake(100, 100, 200, 30)];
[self.view addSubview:slider];
注意:控件的高度是不变的higth=30;
属性
设置最大值
slider.maximumValue=100;
最小值
slider.minimumValue=1;
当前值
slider.value =10;
事件处理
[slider addTarget:self action:@selector(dealSlider:) forControlEvents:UIControlEventValueChanged];
}
-(void)dealSlider:(UISlider *)s
{
NSLog(@”value=%f”,s.value);
}

UISegmentedControl 分段选择

需求:游戏中选择种族
UISegmentedControl *sc=[[UISegmentedControl alloc]initWithItems:@[@”人族”,@”精灵族”,@”矮人”,@”兽人”,@”迈雅”]];
sc.frame=CGRectMake(10, 100, 300, 30);
[self.view addSubview:sc];
属性
当前选择项
sc.selectedSegmentIndex=2;
设置色调
sc.tintColor=[UIColor redColor];
插入一个段
[sc insertSegmentWithTitle:@”亡灵族” atIndex:5 animated:YES];
事件处理
[sc addTarget:self action:@selector(dealSc:) forControlEvents:UIControlEventValueChanged];
}
-(void)dealSc:(UISegmentedControl *)sc
{
NSLog(@”sc=%d”,sc.selectedSegmentIndex);
}
UIStepper 计数器/步进器

需求:购买界面上添加控件,选择构面数量
UIStepper *stepper=[[UIStepper alloc]init];
stepper.center=CGPointMake(250, 100);
[self.view addSubview:stepper];
[stepper addTarget:self action:@selector(dealSteeper:) forControlEvents:UIControlEventValueChanged];
stepper.minimumValue=1;
stepper.maximumValue=100;
stepper.value=1;

textField=[[UITextField alloc]initWithFrame:CGRectMake(10, 85, 190, 30)];
textField.borderStyle=UITextBorderStyleRoundedRect;
textField.text=@”1”;
textField.delegate=self;
[self.view addSubview:textField];

}
-(void)dealSteeper:(UIStepper *)steeper
{
NSLog(@”%f”,steeper.value);
textField.text=[NSString stringWithFormat:@”%d”,(int)steeper.value];
}

UIProcessView 进度条

常用显示耗时任务,的完成进度
数据下载,载入文件,游戏加载
UIProgressView *progressView=[[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
progressView.frame=CGRectMake(20, 100, 280, 30);
[self.view addSubview:progressView];

模拟网路下载
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(dealProgress:) userInfo:progressView repeats:YES];

}
-(void)dealProgress:(NSTimer *)timer
{
UIProgressView *pv=timer.userInfo;
进度条当前进度0.0~1.0;
pv.progress+=0.02;

}

UITextView 文本视图
textView=[[UITextView alloc]initWithFrame:CGRectMake(10, 40, 300, 430)];
[self.view addSubview:textView];
textView.text=@”致虚级,守静笃,万物并作,无以归复。致虚级,守静笃,万物并作,无以归复。”;
textView.font=[UIFont systemFontOfSize:24];
如何回收键盘
输入框按return时候不是结束,而是换行
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
textView.inputAccessoryView=view;
UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
button.frame=CGRectMake(260, 7, 60, 30);
[button setTitle:@”返回” forState:UIControlStateNormal];
[button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];

}
-(void)btnClick:(UIButton *)button
{
[textView resignFirstResponder];
}

UIActionSheet 动作列表

UIButton *shareButton=[UIButton buttonWithType:UIButtonTypeSystem];
[self.view addSubview:shareButton];
[shareButton setTitle:@”分享” forState:UIControlStateNormal];
shareButton.frame=CGRectMake(100, 100, 100, 30);
[shareButton addTarget:self action:@selector(dealShare:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)dealShare:(UIButton *)button
{
UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@”分享” delegate:self cancelButtonTitle:@”取消” destructiveButtonTitle:nil otherButtonTitles:@”新浪微博”,@”微信圈子”,@”微信好友”,@”邮件”,@”短信”, nil];
显示出来。
[actionSheet showInView:self.view];

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
可以知道点击了第几项。
NSLog(@”点击了第%d个按钮”,buttonIndex);

}

UIAlertView 警告视图
可以输入用户名和密码的输入
UIAlertView *alertView = [[UIAlertView alloc] init];
alertView.title = @”输入用户名和密码”;
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[alertView addButtonWithTitle:@”取消”];
[alertView addButtonWithTitle:@”完成”];
[alertView show];
alertView.delegate = self;
}

  • (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
    {
    UITextField *nameText = [alertView textFieldAtIndex:0];
    UITextField *passwordText = [alertView textFieldAtIndex:1];

NSLog(@”name:%@ pass:%@”,nameText.text,passwordText.text);
}

如何使用标签栏控制器实现多界面的切换

创建多个试图控制器
创建一个标签栏控制器
UITabBarController *tbc=[[UITabBarController alloc]init];
把前面创建的试图控制器放入标签栏控制器中管理
tbc.viewControllers=@[frist,second,thir,fou,fiv,six];
标签栏一般同时最多显示5个界面,如果大于5个,最后一个标签项变成more中,

标签栏上标签项的设置

可以在标签栏上设置文本和图片
注意:标签栏显示该界面的时候从tabBarItem中取出需要的title和Image
fvc.tabBarItem.title=@”Limt”;
fvc.tabBarItem.image=[UIImage imageNamed:@”tabbar_limitfree”];
自己创建标签项。
UITabBarItem *item=[[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemBookmarks tag:100];
fvc.tabBarItem=item;
可以控制图片拉伸和上下移动
fvc.tabBarItem.imageInsets=UIEdgeInsetsMake(10, 0, 0, 0);
设置徽标。
fvc.tabBarItem.badgeValue=@”10”;

标签栏的设置

设置色调
tab.tabBar.barTintColor=[UIColor yellowColor];
设置背景图
tab.tabBar.backgroundImage=[UIImage imageNamed:@”tabbar_bg”];
设置标签被选中状态颜色
tab.tabBar.selectedImageTintColor=[UIColor purpleColor];

标签栏控制器的 时间处理

想要禁止选择某个标签项
当某个试图被选择的时候执行,返回yes执行,返回no不执行
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
选择了某个标签项进行处理
当某个试图被选中的时候执行
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController

标签栏定制

核心:隐藏系统原来的标签栏,添加上自己定义的View;
创建一个标签栏控制器(TabBarContorller类)
把系统的替换成自己创建的tabBarContorller
1.先隐藏标签栏
self.tabBar.hidden=YES;
2.创建自己的标签栏。tabBar
获得屏幕的大小尺寸
CGSize size=[UIScreen mainScreen].bounds.size;
UIView *tabBar=[[UIView alloc]initWithFrame:CGRectMake(0, size.height-49, size.width, 49)];
tabBar.backgroundColor=[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
[self.view addSubview:tabBar];
点击事件中实现切换界面的功能。
int index=button.tag-100;
index表示按钮的序号
selectedIndex表示被选中的序号。
self.selectedIndex=index;
获取被选择界面的序号
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
int index=[ud integerForKey:@”selectedIndex”];
tab.selectedIndex=index;

保存被选择界面的序号

NSUserDefaults 系统提供保存数据一种机制(单例)
NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
[ud setInteger:self.selectedIndex forKey:@”selectedIndex”];
tbc.selectedIndex = index;

隐藏状态栏

先设置plist文件中的
View controller-based=NO;
[UIApplication sharedApplication].statusBarHidden=NO;

设置状态栏文字为白色

只有两种颜色
default是黑色
LightContent为白色。
[UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@”header_bg”] forBarMetrics:UIBarMetricsDefault];