根據(jù)拖動手勢的實時位置實現(xiàn)可拖動的button
代碼如下:
/// 可以隨意拖動位置的按鈕組件
classSGMoveButton: UIButton
{
// MARK: - properties
varparentView:UIView?;
// MARK: - life cycle
override init(frame:CGRect)
{
super.init(frame:frame);
letrecognizer:UIPanGestureRecognizer = UIPanGestureRecognizer(target:self,action: #selector(SGMoveButton.eventPanGestureRecognizerHandler(_:)));
self.addGestureRecognizer(recognizer);
}
required init?(coderaDecoder:NSCoder)
{
super.init(coder:aDecoder);
}
deinit
{
}
// MARK: - public methods
// MARK: - event response
internal func eventPanGestureRecognizerHandler(_sender:UIPanGestureRecognizer)
{
if(sender.state== UIGestureRecognizerState.changed)
{
letcurrentPoint:CGPoint = sender.translation(in:self.parentView);// 獲得pan手勢相對于parentView移動的CGPoint
self.center= CGPoint(x:self.center.x+ currentPoint.x,y:self.center.y+ currentPoint.y);// 按照上面相對移動的CGPoint改變button的CGPoint
sender.setTranslation(CGPoint.zero,in:self.parentView);// 將pan手勢相對于parentView的CGPoint置零
}
}
}