轻拍手势识别器不工作.....?

时间:2017-11-15 00:33:09

标签: swift uitapgesturerecognizer

我不得不创建一个新线程bcoz它让我疯狂,所有其他在线答案都完全一样。我已经无数次地完成了这件事,但我无法看到我为生命而失踪的东西。我正在使用"测试"查看控制器只是为了让点击手势工作,但它根本不起作用......我相当确定我正确设置了这个,因为这是我过去总是实现它的方式: (是的,我已经选中了isUserInteractionEnabled的方框)。我甚至在一个不同的viewcontroller上以这种方式实现它,它正在工作......

class TestViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.addGestureRecognizer(tap)
}

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))


@objc func wasTapped() {
    print("tapped")
}

}

我也尝试将参数添加到wasTapped:

 @objc func wasTapped(gestureRecognizer: UITapGestureRecognizer) {
    print("tapped")
}

4 个答案:

答案 0 :(得分:5)

尝试这样的事情

override func viewDidLoad() {
    super.viewDidLoad()

     let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped(sender:)))
     tap.numberOfTapsRequired = 1 // Default value
     view.isUserInteractionEnabled = true
     view.addGestureRecognizer(tap)

}

@objc func wasTapped(sender: UITapGestureRecognizer) {
    print("tapped")
}

答案 1 :(得分:3)

如果要对标准UIView

使用手势识别器,则必须启用交互

view.isUserInteractionEnabled

中添加viewDidLoad = true

答案 2 :(得分:3)

你在说:

override func viewDidLoad() {
    super.viewDidLoad()

    view.addGestureRecognizer(tap)
}

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

问题是最后一行:

let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))

你不能只是在不知名的地方说let tap。您隐式地创建了一个实例属性。但是,您无法初始化目标为self的实例属性,因为初始化实例属性时self不存在。 (我认为这个代码甚至可以编译为bug,并且已经报告过它。)

将该行移至viewDidLoad的开头,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped))
    view.addGestureRecognizer(tap)
}

答案 3 :(得分:0)

var tapGesture = UITapGestureRecognizer()

观看并设置IBOutlet,如:

@IBOutlet weak var viewTap: UIView!     

在viewDidLoad()上编写漂亮的代码,如:

tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myviewTapped(_:)))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.numberOfTouchesRequired = 1
    viewTap.addGestureRecognizer(tapGesture)
    viewTap.isUserInteractionEnabled = true

当点击手势识别时,此方法正在调用

  @objc func myviewTapped(_ sender: UITapGestureRecognizer) {

    if self.viewTap.backgroundColor == UIColor.yellow {
        self.viewTap.backgroundColor = UIColor.green
    }else{
        self.viewTap.backgroundColor = UIColor.yellow
    }
}