我以编程方式制作了一个子视图,它显示在我的主视图中。它还有一个单独的视图控制器。 虽然我的gestureRecognizers在主视图中处理UIImageViews,但它们在我的子视图中不起作用。
这是我在主视图控制器中的内容:
var hVC: HandViewController = HandViewController()
override func viewDidLoad() {
super.viewDidLoad()
createHandImageView()
}
func createHandImageView() {
addChildViewController(hVC)
let w: CGFloat = cardWidth + ((hVC.maxHandCards-1) * hVC.handCardSep)
let h: CGFloat = cardHeight
let screenWidth = view.frame.size.width
let screenHeight = view.frame.size.height
let x: CGFloat = (screenWidth - w) / 2
let frame = CGRectMake(x, screenHeight - cardHeight - 20, w, h)
hVC.view = UIImageView(frame: frame)
hVC.view.backgroundColor = UIColor(white: 0, alpha: 0.3)
// This is where I add the Hand View that eventually holds the card views
view.addSubview(hVC.view)
hVC.didMoveToParentViewController(self)
}
子视图控制器:
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad() // This NEVER fires
NSLog("did load");
}
func updateHandCardsView(cards: [Int]) {
handCardViews = [];
for card in cards {
addNewHandCardImage(card)
}
}
func addNewHandCardImage(card: Int) {
let imageView = UIImageView(frame:CGRectMake(0, 0, cardWidth, cardHeight));
imageView.image = UIImage(named: Deck.getCardName(card))
// This is where I add each Card View to the Hand View
self.view.addSubview(imageView)
handCardViews.append(imageView)
addEventRecognizers(imageView)
}
func addEventRecognizers(view: UIImageView) {
let singleTap = UITapGestureRecognizer(target: self, action: "highlightCard:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
view.userInteractionEnabled = true
view.addGestureRecognizer(singleTap)
let doubleTap = UITapGestureRecognizer(target: self, action: "playCard:")
doubleTap.numberOfTapsRequired = 2
doubleTap.numberOfTouchesRequired = 1
view.userInteractionEnabled = true
view.addGestureRecognizer(doubleTap)
}
所有卡片视图都显示在手形视图中。全部以编程方式创建。 当我将手势代码复制并粘贴到主视图中并在桌面上的卡片上使用时,将调用该操作,但不会在子视图(HandView)中调用。
我错过了什么?
答案 0 :(得分:1)
手势识别器仅适用于他们所属的视图。有一个UIView方法来添加手势识别器。你的addEventRecognizers只是为传入的任何UIImageView添加识别器。你应该更改函数调用以接受UIView,因为UIImageView只是UIView的子类,它仍然适用于你的图像。然后拨打
addEventRecognizers(HandView) //Pass in the view that will get set with gesture recognizer.
或者,如果您只想添加一个手势识别器,只需拨打HandView.addGestureRecognizer(gesture)