iOS-UIDynamic物理模擬-附著-UIAttachmentBehavior
阿新 • • 發佈:2019-02-16
附著-UIAttachmentBehavior
物理模擬中的附著行為的實現同之前’捕捉’步驟
1.建立物理模擬器物件
2.建立物理模擬行為物件
3.設定物理模擬行為的屬性
4.將模擬行為新增到物理模擬器中
@property (weak, nonatomic) IBOutlet UIView *testViewOne;
@property (weak, nonatomic) IBOutlet UIView *testViewTwo;
@property (nonatomic, strong) UIDynamicAnimator *animator;
- (void )viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.testViewOne.layer.cornerRadius = 25;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewDidTapGesture:)];
[self .view addGestureRecognizer:tapGesture];
}
- (void)viewDidTapGesture:(UIPanGestureRecognizer *)tapGesture {
CGPoint currentPanPoint = [tapGesture locationInView:self.view];
//建立物理模擬器
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
//建立重力模擬行為
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[self .testViewOne, self.testViewTwo]];
//設定重力模擬行為的屬性(引數)
// CGVector gravityDirection
// CGFloat angle
// CGFloat magnitude
gravity.gravityDirection = CGVectorMake(0, 1);
gravity.magnitude = 1;
ZHJView *view = (ZHJView *)self.view;
[gravity setAction:^{
view.startPoint = currentPanPoint;
view.endPointOne = self.testViewOne.center;
CGPoint point = CGPointZero;
view.endPointTwo = [self.view convertPoint:point fromView:self.testViewTwo];
}];
//建立附著模擬行為
UIAttachmentBehavior *attachmentOne = [[UIAttachmentBehavior alloc] initWithItem:self.testViewOne attachedToAnchor:currentPanPoint];
//UIAttachmentBehavior *attachmentTwo = [[UIAttachmentBehavior alloc] initWithItem:self.testViewTwo attachedToAnchor:currentPanPoint];
//預設是和物體的中心點附著...修改中心點的偏移量 ,附著左上角
CGSize size = self.testViewTwo.bounds.size; //myView的size
UIOffset offset = UIOffsetMake(- size.width * 0.5, - size.height * 0.5);
UIAttachmentBehavior *attachmentTwo = [[UIAttachmentBehavior alloc] initWithItem:self.testViewTwo offsetFromCenter:offset attachedToAnchor:currentPanPoint];
//新增模擬行為
[self.animator addBehavior:gravity];
[self.animator addBehavior:attachmentOne];
[self.animator addBehavior:attachmentTwo];
// [self.animator addBehavior:collision];
}
其中要注意的點可能就是控制元件和觸控點選點間的連線繪製,這裡要自定義一個view(我定義的是ZHJView)的類來描述控制器viewController的View
在ZHJView類中獲取手指觸控的點以及控制元件的錨點
在.h檔案中宣告
@property (nonatomic, assign) CGPoint startPoint;
@property (nonatomic, assign) CGPoint endPointOne;
@property (nonatomic, assign) CGPoint endPointTwo;
在.m檔案中重寫startPoint的set方法以及drawRect: ,因為drawRect:方法不能手動呼叫,所以在設定startPoint的時候需要重繪,見程式碼
- (void)setStartPoint:(CGPoint)startPoint {
_startPoint = startPoint;
//重繪
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
//建立Bezier路徑
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:self.startPoint];
[path addLineToPoint:self.endPointOne];
[path moveToPoint:self.startPoint];
[path addLineToPoint:self.endPointTwo];
//描邊
[path stroke];
}
物理模擬原始碼下載