生活随笔
收集整理的這篇文章主要介紹了
iOS手势操作简介(五)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
利用手勢操作實(shí)現(xiàn)抽屜效果:
第一步:搭建UI
(void)addChildView
{
// left
UIView *leftView = [[UIView alloc] initWithFrame:self.view.bounds];
leftView.backgroundColor = [UIColor greenColor];
[self.view addSubview:leftView];
_leftView = leftView;
// right
UIView *rightView = [[UIView alloc] initWithFrame:self.view.bounds];
rightView.backgroundColor = [UIColor blueColor];
[self.view addSubview:rightView];
_rightView = rightView;// mainView
UIView *mainView = [[UIView alloc] initWithFrame:self.view.bounds];
mainView.backgroundColor = [UIColor redColor];
[self.view addSubview:mainView];
_mainView = mainView;
}
第二步:獲取手勢操作對(duì)象,獲取手勢移動(dòng)大小
- (void)touchesMoved:(NSSet )touches withEvent:(UIEvent )event
{
// 獲取UITouch對(duì)象
UITouch *touch = [touches anyObject];
// 獲取當(dāng)前點(diǎn)
CGPoint currentPoint = [touch locationInView:self.view];// 獲取上一個(gè)點(diǎn)
CGPoint prePoint = [touch previousLocationInView:self.view];// x軸偏移量:當(dāng)手指移動(dòng)一點(diǎn)的時(shí)候,x偏移多少
CGFloat offsetX = currentPoint.x - prePoint.x;// 設(shè)置當(dāng)前主視圖的frame
_mainView.frame = [self getCurrentFrameWithOffsetX:offsetX];_isDraging = YES;
}
第三步:利用手勢平移量來重寫計(jì)算新的frame
//#define HMMaxY 60
// 當(dāng)手指偏移一點(diǎn),根據(jù)X軸的偏移量算出當(dāng)前主視圖的frame
- (CGRect)getCurrentFrameWithOffsetX:(CGFloat)offsetX
{
CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
// 獲取y軸偏移量,手指每移動(dòng)一點(diǎn),y軸偏移多少
CGFloat offsetY = offsetX * HMMaxY / screenW;CGFloat scale = (screenH - 2 * offsetY) / screenH;if (_mainView.frame.origin.x < 0) { // 往左邊滑動(dòng)scale = (screenH + 2 * offsetY) / screenH;
}// 獲取之前的frame
CGRect frame = _mainView.frame;
frame.origin.x += offsetX;
frame.size.height = frame.size.height *scale;
frame.size.width = frame.size.width *scale;
frame.origin.y = (screenH - frame.size.height) * 0.5;return frame;
}
第四步:定位于復(fù)位業(yè)務(wù)邏輯
//#define HMRTarget 250
//#define HMLTarget -220
/*
_mainView.frame.origin.x > screenW * 0.5 定位到右邊
CGRectGetMaxX(_mainView.frame) < screenW * 0.5 定位到左邊 -220
*/
// 定位
- (void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event
{
// 復(fù)位
if (_isDraging == NO && _mainView.frame.origin.x != 0) {[UIView animateWithDuration:0.25 animations:^{_mainView.frame = self.view.bounds;}];
}CGFloat screenW = [UIScreen mainScreen].bounds.size.width;CGFloat target = 0;
if (_mainView.frame.origin.x > screenW * 0.5) { // 定位到右邊target = HMRTarget;
}else if (CGRectGetMaxX(_mainView.frame) < screenW * 0.5) { // 定位到左邊target = HMLTarget;
}[UIView animateWithDuration:0.25 animations:^{if (target) { // 在需要定位左邊或者右邊// 獲取x軸偏移量CGFloat offsetX = target - _mainView.frame.origin.x;// 設(shè)置當(dāng)前主視圖的frame_mainView.frame = [self getCurrentFrameWithOffsetX:offsetX];}else{ // 還原_mainView.frame = self.view.bounds;}
}];_isDraging = NO;
}
總結(jié)
以上是生活随笔為你收集整理的iOS手势操作简介(五)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。