问题描述
我在ViewController视图上添加了UIView卡:
self.view.addSubview(cardView)
cardView.anchor(top: self.topWhiteView.bottomAnchor,leading: view.leadingAnchor,bottom: buttonsStackView.topAnchor,trailing: view.trailingAnchor,padding: .init(top: 15,left: 10,bottom: 10,right: 10))
我在上面添加了panGestureRecogniser,可以用来拖动卡。 平移方法:
@objc func handlePan(gesture : UIPanGestureRecognizer){
switch gesture.state {
case .changed:
handleChanged(gesture)
case .ended:
handleEnded(gesture)
default:
()
}
}
fileprivate func handleChanged(_ gesture: UIPanGestureRecognizer) {
let translationY = gesture.translation(in: nil).y
var scaleValue : CGFloat = 1
let multiplier = 1.1*translationY
if translationY != 0 {
scaleValue = 1 - (abs(translationY*multiplier)/abs(translationY)/3000)
}
let scale = CGAffineTransform(scaleX: scaleValue,y: scaleValue)
let translation = gesture.translation(in: nil)
let rotationRadiant: CGFloat = translation.x / 20
let rotationDegree = (rotationRadiant * .pi) / 180
let rotationalTransformation = CGAffineTransform(rotationAngle: rotationDegree)
self.transform = rotationalTransformation.translatedBy(x: translation.x,y: translation.y).concatenating(scale)
}
fileprivate func handleEnded(_ gesture: UIPanGestureRecognizer) {
UIView.animate(withDuration: 0.6,delay: 0,usingSpringWithDamping: 0.6,initialSpringVelocity: 0.1,options: [.curveEaseOut,.allowUserInteraction],animations: {
self.transform = CGAffineTransform.identity
})
}
我想知道每当卡片移动时如何检测cardView的中心位置。
但与其他Stack Overflow问题不同,我想在cardView类中进行操作,而不使用任何委托。
解决方法
不确定我是否完全了解您的需求,但是请尝试以下操作
class CardView: UIView {
override var center: CGPoint {
get { super.center }
set {
super.center = newValue
didMove(to: newValue)
}
}
private func didMove(to point: CGPoint) {
// do anything needed with new position
}
}