我有一个带有图片的视图,在touchBegan
上我使用CGAffineTransform
将按钮缩小到0.8
在我的ViewController
我为视图添加了panGesturdeRecognizer
。
您只能在Y轴上移动按钮。
我的问题是在平移子视图图像时向左移动时更改视图的中心点。
class QTView: UIView {
lazy var image: UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "image")
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIView.animate(withDuration: 0.3, animations: {
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.layoutIfNeeded()
})
}
}
extension QTView {
fileprivate func initialize() {
addSubview(image)
backgroundColor = UIColor.white
//border
layer.borderColor = UIColor.blue.cgColor
layer.borderWidth = 3
NSLayoutConstraint.activate([
image.centerXAnchor.constraint(equalTo: centerXAnchor),
image.centerYAnchor.constraint(equalTo: centerYAnchor),
image.widthAnchor.constraint(equalToConstant: 30),
image.heightAnchor.constraint(equalToConstant: 30)
])
}
}
的ViewController:
func OnPanListener(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.customView)
guard let view = recognizer.view else {
recognizer.setTranslation(CGPoint.zero, in: self.view)
return
}
//*0.8 because of scale animation
let newY = view.center.y + (translation.y*0.8)
view.center = CGPoint(x: view.center.x, y: newY)
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
这有什么建议吗? 感谢