在Swift中创建可重用的View并添加完成处理程序

时间:2019-02-11 15:43:10

标签: ios swift completionhandler

我创建了一个sliderView,并添加了一个UIPanGesture,并且创建了一个单独的UIView来处理此滑块。我希望能够在需要的其他ViewControllers中调用此SliderView,但是当我尝试运行我的代码时,IT崩溃了。我还希望传递一个完成处理程序,以处理需要的ViewCOntrollers中的事件。我试图通过创建一个UIView并在多个屏幕中使用它来遵循DRY过程。下面是到目前为止的代码

class TripView: UIView {

    var shouldSetupConstraints = true
    var startingFrame: CGRect?

    var sliderView: UIView!
    var sliderImage: UIImageView!

    let screenSize = UIScreen.main.bounds

    override init(frame: CGRect){
        super.init(frame: frame)
        swipeFunc()
        sliderView = UIImageView(frame: CGRect.zero)
        sliderView.backgroundColor = UIColor.green

        sliderView.autoSetDimension(.height, toSize: screenSize.width / 6)

        self.addSubview(sliderView)

        sliderImage = UIImageView(frame: CGRect.zero)
        sliderImage.backgroundColor = UIColor.clear
        sliderImage.image = UIImage(named: "icons8-double_right_filled.png")
        sliderImage.contentMode = .scaleAspectFit

        sliderImage.autoSetDimension(.width, toSize: screenSize.width / 6)
        sliderImage.autoSetDimension(.height, toSize: screenSize.width / 6)

        self.addSubview(sliderImage)


    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func updateConstraints() {
        if(shouldSetupConstraints) {

            sliderView.autoPinEdgesToSuperviewSafeArea(with: UIEdgeInsets.zero, excludingEdge: .bottom)
            sliderImage.autoPinEdge(toSuperviewEdge: .left)
            sliderImage.autoPinEdge(.bottom, to: .bottom, of: sliderView, withOffset: 0.0)

            shouldSetupConstraints = false
        }

        super.updateConstraints()
    }
}

extension TripView {

    private func swipeFunc() {

        let swipeGesture = UIPanGestureRecognizer(target: self, action: #selector(acknowledgeSwiped(sender:)))
        sliderImage.addGestureRecognizer(swipeGesture)
        sliderImage.isUserInteractionEnabled = true
        swipeGesture.delegate = self as? UIGestureRecognizerDelegate
    }

    @objc func acknowledgeSwiped(sender: UIPanGestureRecognizer) {
        if let sliderView = sender.view {
            let translation = sender.translation(in: sliderView)
            switch sender.state {
            case .began:
                startingFrame = sliderImage.frame
                fallthrough
            case .changed:
                if let startFrame = startingFrame {

                    var movex = translation.x
                    if movex < -startFrame.origin.x { movex = -startFrame.origin.x }

                    let xMax = sliderView.frame.width - startFrame.origin.x - startFrame.width
                    if movex > xMax {
                        movex = xMax

      // I WANT TO PASS A COMPLETION HANDLER HERE. TO BE ABLE TO HANDLE OTHER     EVENTS IN VIEWCONTROLLERS

                    }

                    var movey = translation.y
                    if movey < -startFrame.origin.y { movey = -startFrame.origin.y }

                    let yMax = sliderView.frame.height - startFrame.origin.y - startFrame.height
                    if movey > yMax {
                        movey = yMax

                    }

                    sliderView.transform = CGAffineTransform(translationX: movex, y: movey)
                }
            default: // .ended and others:
                UIView.animate(withDuration: 0.1, animations: {
                    sliderView.transform = CGAffineTransform.identity
                })
            }
        }
    }

}

2 个答案:

答案 0 :(得分:2)

您可以将完成处理程序添加为内部变量,也可以在初始化程序中传递一个。

例如:

class TripView: UIView {
    typealias Callback = () -> ()
    var callback: Callback

    ...
}

然后您要在其中触发回调的地方,只需调用:

callback()

或者您可以定义一个委托

protocol TripViewDelegate {
    func didDoSomething(for view: TripView)
}

class TripView: UIView {
    weak var tripViewDelegate: TripViewDelegate?
    // ...
}

然后致电

tripViewDelegate?.didDoSomething(for: self)

答案 1 :(得分:1)

您正在呼叫swipeFunc,该电话在初始化sliderImage之前访问sliderImage

您必须将swipeFunc()移动到init方法的末尾。

实际上,不需要使用隐式展开的可选。您可以使用非可选选项来防止崩溃:

let sliderView: UIView = UIImageView(frame: CGRect.zero)
let sliderImage: UIImageView = UIImageView(frame: CGRect.zero)

由于您实际上有两个初始化程序,因此您可能应该同时初始化两个初始化程序:

let sliderView: UIView = UIImageView(frame: CGRect.zero)
let sliderImage: UIImageView = UIImageView(frame: CGRect.zero)

override init(frame: CGRect){
    super.init(frame: frame)

    commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    commonInit()
}

private func commonInit() {
    sliderView.backgroundColor = UIColor.green
    sliderView.autoSetDimension(.height, toSize: screenSize.width / 6)

    self.addSubview(sliderView)

    sliderImage.backgroundColor = UIColor.clear
    sliderImage.image = UIImage(named: "icons8-double_right_filled.png")
    sliderImage.contentMode = .scaleAspectFit

    sliderImage.autoSetDimension(.width, toSize: screenSize.width / 6)
    sliderImage.autoSetDimension(.height, toSize: screenSize.width / 6)

    self.addSubview(sliderImage)

    swipeFunc()
}

关于回调,只需声明一个属性:

class TripView: UIView {
    var onChange: (() -> Void)?
}

以及每次更改请求:

onChange?()

然后,您可以在控制器中:

var tripView: TripView = ...
tripView.onChange = {
  // handle the event
}