我正在尝试将完整功能的滑动手势代码移动到view model
以清理view controller
,但代码使用了大量self
和view
引用,所以我想我需要在调用函数时传递view
或UIView.self
作为参数。虽然不能让它工作。尝试:
vm.swipeCode(myView: self.view)
func swipeCode(myView: UIView) {...
但它崩溃了。经过一些研究后,我也尝试了inout
和&
的变体,但无济于事。这是完整的滑动代码(它引用回view controller
但我会在事情开始工作时移动它们:))
var myVC = RecipesViewController()
func swipeCode(myView: UIView) {
//SWIPE RIGHT
let swipingRight = UISwipeGestureRecognizer()
swipingRight.addTarget(self, action: #selector(myVC.swipeRight))
swipingRight.direction = .right
swipingRight.delegate = self as? UIGestureRecognizerDelegate
swipingRight.cancelsTouchesInView = false
myView.isUserInteractionEnabled = true
myView.addGestureRecognizer(swipingRight)
//// ALLOW SWIPE LEFT ////
let swipingLeft = UISwipeGestureRecognizer()
swipingLeft.addTarget(self, action: #selector(myVC.swipeLeft))
swipingLeft.direction = .left
swipingLeft.delegate = self as? UIGestureRecognizerDelegate
swipingLeft.cancelsTouchesInView = false
myView.isUserInteractionEnabled = true
myView.addGestureRecognizer(swipingLeft)
}
答案 0 :(得分:0)
如果您的方法使用了大量UIView
,那么您只需创建一个UIViewController
或self
继承的类,然后只需创建该类的控制器或视图。
class CustomViewController:UIViewController {
func swipeCode(myView: UIView) {
// Your code here
}
// Any other methods your code might need
}
class RecipesViewController:CustomViewController {
// Whatever else your view controller is made from
}
或者,如果您的代码滑动适用于每个视图控制器,您还可以扩展UIViewController
以添加这些功能
答案 1 :(得分:0)
崩溃可能是因为这两行:
swipingRight.addTarget(self, action: #selector(myVC.swipeRight))
swipingLeft.addTarget(self, action: #selector(myVC.swipeLeft))
您已将myVC.swipeLeft
作为操作,但self
作为目标,因此手势识别器会尝试在swipeLeft
中找到self
方法,但不会存在。
您应该始终确保该操作是目标的成员:
swipingRight.addTarget(myVC, action: #selector(myVC.swipeRight))
swipingLeft.addTarget(myVC, action: #selector(myVC.swipeLeft))