[英]How to add gesture recognizer to custom UIView (XIB) programmatically?
[英]Add UI Gesture Recognizer to UIView instantiated from .xib
我正在使用Xcode 10.0 beta 4和Swift 4,我想为左右滑动向UIView添加UIGestureRecognizers,特别是UISwipeGestureRecognizer,该UIView已通过笔尖作为子视图添加到主视图控制器中,但不幸的是当我实际在模拟器中执行操作时,似乎无法识别该手势。 这是我的viewDidLoad()中的代码片段:
//Add gesture recognizer for when the calendar is swiped right.
let grSwipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRight(sender:)))
grSwipeRight.direction = UISwipeGestureRecognizer.Direction.right
calendar.calendarDays.isUserInteractionEnabled = true
calendar.calendarDays.addGestureRecognizer(grSwipeRight)
选择器中的swipeRight操作是对仅包含print()调用的函数,日历是对我的UIView的引用,这是我的.xib中使用的类
class Calendar: UIView
{
@IBOutlet var calendarDays: UICollectionView!
let nibName = "Calendar"
var contentView: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = self.loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
self.bringSubviewToFront(view)
contentView = view
contentView?.isUserInteractionEnabled = true
}
private func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
我使用Interface Builder将.xib设置为UIView,并将视图的类设置为Calendar类,并且在.xib中的此类标签在我将任何手势识别器添加到calendar(View)或日历中的对象无法识别手势。 这是做这样事情的正确方法还是我应该采取一种完全不同的方法?
为了能够在我的.xib中使用手势识别器,我在自定义UIView Calendar类中使用了awakeFromNib()的重写:
override func awakeFromNib()
{
super.awakeFromNib()
let touchTest = UITapGestureRecognizer(target: self, action: #selector(self.testTap(sender:)))
testingLabel.isUserInteractionEnabled = true
testingLabel.addGestureRecognizer(touchTest)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.