iOS開發入門之——可拖動視圖

預備知識

iOS處理屏幕上的觸摸動作,主要涉及到以下幾個方法:

touchesBegan:withEvent:          //觸摸屏幕的最開始被調用

touchesMoved:withEvent:         //移動過程中被調用

touchesEnded:withEvent:         //動作結束時被調用

touchesCancelled:WithEvent:

從方法的命名可以清晰的看出該方法何時被調用,最後一個比較特殊。touchesCancelled:WithEvent:Cocoa Touch必須響應持續觸摸事件的系統中斷時調用。

我們只要重寫這些方法,來作我們想要作的事情就可以了。


如何實現拖動視圖?

1.設置userInteractionEnabled屬性爲YES,允許用戶交互。
2.在觸摸動作開始時記錄起始點。
3.在移動過程中,計算當前位置座標與起始點的差值,即偏移量,並且移動視圖中心點至偏移量大小的地方。
4.分別限制x座標、與y座標,保證用戶不可將視圖出屏幕

備註:分別限制x座標與y座標的原因是,即使向右拖動不了了,仍需保證可以向下拖動。


實現代碼

以子類化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  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章