UIPanGestureRecognizer в подклассе UIView

Я пытался больше опираться на подклассы определенных объектов. Теперь я создал подкласс UIView, у которого есть PanGestureRecognizer для смахивания влево и вправо.

Не могу найти проблему. Он даже не сдвинет UIView. Я пытался посмотреть жизненный цикл UIView, чтобы установить isUserInteractionEnabled в true, но безрезультатно. См. код ниже:

ВК

import UIKit

class SwipeViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    addNewProfile()
}

private func addNewProfile() {

    let swipeView = SwiperView(frame: CGRect(x: self.view.bounds.width / 2 - 150, y: self.view.bounds.height / 2 - 75, width: 300, height: 150))
    swipeView.parentView = self.view
    swipeView.delegate = self
    swipeView.shadow = true
    swipeView.isUserInteractionEnabled = true
    swipeView.backgroundColor = UIColor.white
    swipeView.alpha = 0.0
    view.addSubview(swipeView)

    UIView.animate(withDuration: 0.3, animations: {
        swipeView.alpha = 1.0
    }, completion: { (succeed) in
        swipeView.isUserInteractionEnabled = true
    })
}
}

//MARK: - ChosenSwipeResultDelegate
extension SwipeViewController: ChosenSwipeResultDelegate {

    func pickedLeftSide() {

    }

    func pickedRightSide() {

    }

}

SwiperView

import UIKit

protocol ChosenSwipeResultDelegate {

func pickedLeftSide()
func pickedRightSide()
}

@IBDesignable class SwiperView: UIView {

private var _shadow: Bool!
private var _parentView: UIView!

var delegate: ChosenSwipeResultDelegate?

var parentView: UIView {
    set {
        _parentView = newValue
    }
    get {
        return _parentView
    }
}

@IBInspectable var shadow: Bool {
    get {
        return layer.shadowOpacity > 0.0
    }
    set {
        if newValue == true {
            addShadow()
        }
    }
}

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set {
        layer.cornerRadius = newValue

        if shadow == false {
            layer.masksToBounds = true
        }
    }
}

override func setNeedsLayout() {
    super.setNeedsLayout()
    isUserInteractionEnabled = true

}

override func awakeFromNib() {
    super.awakeFromNib()

    isUserInteractionEnabled = true
    let dragGesture = UIPanGestureRecognizer(target: self, action: #selector(SwiperView.dragging(gesture:)))
    addGestureRecognizer(dragGesture)
}

func dragging(gesture: UIPanGestureRecognizer) {

    let translation = gesture.translation(in: parentView)
    let tinderView = gesture.view!

    tinderView.center = CGPoint(x: parentView.bounds.width / 2 + translation.x, y: parentView.bounds.height / 2 + translation.y)

    let xFromCenter = tinderView.center.x - parentView.bounds.width / 2

    let scale = min(100 / abs(xFromCenter), 1)

    var rotation = CGAffineTransform(rotationAngle: xFromCenter / 200)

    let stretch = rotation.scaledBy(x: scale, y: scale)

    tinderView.transform = stretch

    if gesture.state == .ended {

        if tinderView.center.x < 100 {
            print("left")

            UIView.animate(withDuration: 0.3, animations: {
                tinderView.alpha = 0.0
            }, completion: { (succeed) in

                self.delegate?.pickedLeftSide()
            })

        } else if tinderView.center.x > parentView.bounds.width - 100 {

            print("right")

            UIView.animate(withDuration: 0.3, animations: {
                tinderView.alpha = 0.0
            }, completion: { (succeed) in

                self.delegate?.pickedRightSide()
            })
        } else {

            print("Not chosen")

            rotation = CGAffineTransform(rotationAngle: 0)

            let stretch = rotation.scaledBy(x: 1, y: 1)
            tinderView.transform = stretch

            tinderView.center = CGPoint(x: parentView.bounds.width / 2, y: parentView.bounds.height / 2)

        }
    }
}

private func addShadow(shadowColor: CGColor = UIColor.black.cgColor, shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0), shadowOpacity: Float = 0.4, shadowRadius: CGFloat = 3.0) {
    layer.shadowColor = shadowColor
    layer.shadowOffset = shadowOffset
    layer.shadowOpacity = shadowOpacity
    layer.shadowRadius = shadowRadius
}
}

person SwingerDinger    schedule 12.12.2016    source источник
comment
У вас замечательный отладчик. Отлаживать! Посмотрите, звонят ли вашему dragging. Если это так, проверьте значения переменных во время выполнения. Разберитесь сами.   -  person matt    schedule 12.12.2016


Ответы (1)


добавьте этот код в свой SwiperView, посмотрите, решит ли он проблему

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

        isUserInteractionEnabled = true
        let dragGesture = UIPanGestureRecognizer(target: self, action: #selector(SwiperView.dragging(gesture:)))
        addGestureRecognizer(dragGesture)

    }

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

        isUserInteractionEnabled = true
        let dragGesture = UIPanGestureRecognizer(target: self, action: #selector(SwiperView.dragging(gesture:)))
        addGestureRecognizer(dragGesture)
    }
person Mohammadalijf    schedule 12.12.2016
comment
Исправлена ​​проблема! :) По какой причине мне нужно было реализовать это в init frame? - person SwingerDinger; 12.12.2016