如何将视图作为参数传递(swift)

时间:2018-03-17 08:05:10

标签: swift xcode arguments viewmodel swipe

我正在尝试将完整功能的滑动手势代码移动到view model以清理view controller,但代码使用了大量selfview引用,所以我想我需要在调用函数时传递viewUIView.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)
}

2 个答案:

答案 0 :(得分:0)

如果您的方法使用了大量UIView,那么您只需创建一个UIViewControllerself继承的类,然后只需创建该类的控制器或视图。

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))