对不起,如果这个问题有点老了。
您可以继承 UIView 并覆盖 touchesBegan(_ , with) 以保存原始触摸位置
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { print("No touch"); return }
startPoint = touch.location(in: self)
startHeight = heightConstraint.constant
slideDirection = .none
super.touchesBegan(touches, with: event)
}
}
和 touchesMoved(_,with) 在手指滑动视图时更新高度约束。
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { print("touchesMovedno touches"); return }
let endPoint = touch.location(in: self)
let diff = endPoint.y - startPoint.y
// This causes the view to move along the drag
switch anchorLocation {
case .top :
heightConstraint.constant = startHeight + diff
case .bottom :
heightConstraint.constant = startHeight - diff
}
self.layoutIfNeeded()
// Update direction
if diff == 0.0 {
self.slideDirection = .none
} else {
self.slideDirection = (diff > 0) ? .down : .up
}
super.touchesMoved(touches, with: event)
}
如果您愿意,可以覆盖 touchesEnded(_, with) 以添加动画
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.modifyHeightConstraints()
self.animateViewTransition(duration: animDuration, delay: animDelay, clearance: animClearance, springDampingRatio: animSpringDampingRatio, initialSpringVelocity: animInitialSpringVelocity, complete: {
self.slideDirection = .none
})
super.touchesEnded(touches, with: event)
}
我创建了一个组件,它可能具有您想要的确切功能。该组件包括可调整的动画弹跳。您可以在情节提要中的视图上布局和设计子视图。
查看 GitHub 中的链接
https://github.com/narumolp/NMPAnchorOverlayView