iOS开发问题总结

可拖动的button

2017-02-07  本文已影响11人  胜哥的二哥

根据拖动手势的实时位置实现可拖动的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置零

}

}

}

demo地址:https://github.com/songhaisheng/SGMoveButton

上一篇下一篇

猜你喜欢

热点阅读