我以编程方式制作了一个 subview ,它显示在我的主视图中。它还有一个单独的 View Controller 。 虽然我的 gestureRecognizers 在主视图中的 UIImageViews 上工作,但它们在我的 subview 中不起作用。
这是我在主视图 Controller 中的内容:
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)
}
和 subview Controller :
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)
}
所有卡片 View 都显示在手牌 View 中。全部以编程方式创建。 当我将手势代码复制并粘贴到主视图并在 table 上的卡片上使用它时,会调用操作,但不会在 subview (HandView) 中调用。
我错过了什么?
最佳答案
手势识别器仅适用于它们所属的 View 。有一个 UIView 方法来添加手势识别器。您的 addEventRecognizers 仅向传入的 UIImageView 添加识别器。您应该更改函数调用以接受 UIView,因为 UIImageView 只是 UIView 的子类,它仍然可以在您的图像上工作。然后调用
addEventRecognizers(HandView) //Pass in the view that will get set with gesture recognizer.
或者,如果您只想添加一个手势识别器,只需调用 HandView.addGestureRecognizer(gesture)
关于ios - 如何让 UIGestureRecognizer 与手动添加的 subview 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34536940/