准備常識
IOS處置屏幕上的觸摸舉措,重要觸及到以下幾個辦法:
touchesBegan:withEvent: //觸摸屏幕的最開端被挪用
touchesMoved:withEvent: //挪動進程中被挪用
touchesEnded:withEvent: //舉措停止時被挪用
touchesCancelled:WithEvent:
從辦法的定名可以清楚的看出該辦法什麼時候被挪用,最初一個比擬特別。touchesCancelled:WithEvent:在Cocoa Touch必需呼應連續觸摸事宜的體系中止時挪用。
我們只需重寫這些辦法,來作我們想要作的工作便可以了。
若何完成拖動視圖?
1.設置userInteractionEnabled屬性為YES,許可用戶交互。
2.在觸摸舉措開端時記載肇端點。
3.在挪動進程中,盤算以後地位坐標與肇端點的差值,即偏移量,而且挪動視圖中間點至偏移量年夜小的處所。
4.分離限制x坐標、與y坐標,包管用戶弗成將視圖托出屏幕
備注:分離限制x坐標與y坐標的緣由是,即便向右拖動不了了,仍需包管可以向下拖動。
其實,功效比擬簡略,就是IOS手勢動畫中的拖動。來看一下根本的寫法:
1.注冊拖動動畫
UIPanGestureRecognizer * panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithtarget:self
action:@selector(doHandlePanAction:)];
[self.vLight addGestureRecognizer:panGestureRecognizer];
注:vLight就是要參加拖動的View子類。
2.拖動處置函數
- (void) doHandlePanAction:(UIPanGestureRecognizer *)paramSender{
CGPoint point = [paramSender translationInView:self.view];
NSLog(@"X:%f;Y:%f",point.x,point.y);
paramSender.view.center = CGPointMake(paramSender.view.center.x + point.x, paramSender.view.center.y + point.y);
[paramSender setTranslation:CGPointMake(0, 0) inView:self.view];
}
完成代碼
以子類化UIImageView為例
#import <UIKit/UIKit.h>
@interface GragView : UIImageView
{
CGPoint startPoint;
}
@end
#import "GragView.h"
@implementation GragView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
//許可用戶交互
self.userInteractionEnabled = YES;
}
return self;
}
- (id)initWithImage:(UIImage *)image
{
self = [super initWithImage:image];
if (self) {
//許可用戶交互
self.userInteractionEnabled = YES;
}
return self;
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//保留觸摸肇端點地位
CGPoint point = [[touches anyObject] locationInView:self];
startPoint = point;
//該view置於最前
[[self superview] bringSubviewToFront:self];
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//盤算位移=以後地位-肇端地位
CGPoint point = [[touches anyObject] locationInView:self];
float dx = point.x - startPoint.x;
float dy = point.y - startPoint.y;
//盤算挪動後的view中間點
CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
/* 限制用戶弗成將視圖托出屏幕 */
float halfx = CGRectGetMidX(self.bounds);
//x坐標右邊界
newcenter.x = MAX(halfx, newcenter.x);
//x坐標左邊界
newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
//y坐標同理
float halfy = CGRectGetMidY(self.bounds);
newcenter.y = MAX(halfy, newcenter.y);
newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
//挪動view
self.center = newcenter;
}
/*
// Only override drawRect: if you perform custom draWing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// DraWing code
}
*/
@end
【舉例講授iOS開辟中拖動視圖的完成】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!