直接看代码
private let btnWH = 75.0 //按钮宽高
lazy var btn:UIButton = {
let btn = UIButton(frame: CGRect(x: kScreenWidth - 100, y: 300, width: btnWH, height: btnWH))
btn.setImage(UIImage(named: "testimage"), for: .normal)
btn.addTarget(self, action: #selector(clickSuspendBtnAction), for: .touchUpInside)
let pantouch = UIPanGestureRecognizer.init(target: self, action: #selector(handlePan))
btn.addGestureRecognizer(pantouch)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .brown
view.addSubview(btn)
}
@objc func handlePan(recognizer : UIPanGestureRecognizer) {
guard let rView = recognizer.view else {
return
}
let translation = recognizer.translation(in: self.view)
let centerX = rView.center.x + translation.x
var theCenter:CGFloat = 0
rView.center = CGPoint(x: centerX, y: rView.center.y + translation.y)
recognizer.setTranslation(CGPoint.zero, in: self.view)
if recognizer.state == .ended || recognizer.state == .cancelled {
if centerX > (kScreenWidth / 2) {
theCenter = kScreenWidth - btnWH / 2
} else {
theCenter = btnWH / 2
}
var contentOff_Y = rView.center.y
if contentOff_Y > kScreenHeight - kNavBarHeight(self) - 40 {
contentOff_Y = kScreenHeight - kNavBarHeight(self) - 37.5
}
if contentOff_Y < kNavBarHeight(self) + kTabBarHeight(self) {
contentOff_Y = kNavBarHeight(self) + kTabBarHeight(self) + 37.5
}
UIView.animate(withDuration: 0.3) {
rView.center = CGPoint(x: theCenter, y: contentOff_Y + translation.y)
}
}
}
@objc func clickSuspendBtnAction(){
}
版权声明:本文为weixin_43259805原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。