ios - 我如何告诉我的 ViewController 一个 View 被触摸了?

标签 ios iphone objective-c

我正在学习斯坦福 iOS 类(class),并且有一些设计问题。在类里面,我们正在制作一个纸牌配对游戏,屏幕上大约有 20 张纸牌。我最近制作了卡片 UIViews 这样我就可以正确地绘制它们。

我给了他们每个人一个方法tap,它将把faceUp 换成YES/NO,从而翻转卡片。我将手势识别器添加到我的 ViewController 中的每个手势识别器并且它可以工作。单张卡片知道它们何时被触摸和翻转。

但是,我需要在我的 ViewController 中知道 cardView 已被触摸……以及是哪一个。

我必须如何/用什么方法来做到这一点?我可以在我的 View 中广播 ViewController 将监听的内容吗?我可以让我的 viewController 处理点击(但如果我这样做,有没有办法获得发送 View ?)如果这真的很基础,我深表歉意,但我是 iOS 的新手,不想通过修补和实现来学习损坏的 MVC 模式。

编辑:仅供引用,这是我的最终实现。

每个 CardView 上都有一个点击识别器。当识别出点击时,它会调用:

- (void)cardTapped:(UIGestureRecognizer *)gesture
{
    UIView *view = [gesture view]; // This method is what I was looking for. 
    if ([view isKindOfClass:[PlayingCardView class]]) {
        PlayingCardView *playingCardView = (PlayingCardView *)view;
        [playingCardView flip];  // flips card
        // Game code
        if (!self.game.hasStarted) {
            [self startGame];
        }
        int cardIndex = [self.cardViews indexOfObject:playingCardView];
        [self.game chooseCardAtIndex:cardIndex];
        [self updateUI];
    }
}

最佳答案

tag 属性会告诉您哪个 View 被点击了。在创建 View 时设置正确的标记,在点击时触发的操作方法中,您可以调用委托(delegate)方法,该方法将通知您的委托(delegate)人点击了哪个 View 。让您的 View Controller 具有委托(delegate),它将收到通知。

// your target method will look like this:
- (void) didTap:(id)sender {

   //... your code that handle flipping the card

   [self.delegate didTapOnCard:self]; // where delegate is your view controller

}

关于ios - 我如何告诉我的 ViewController 一个 View 被触摸了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22202863/

相关文章:

ios - 在不使用 Google Maps API 的情况下集成 Google Places API?

iphone - 重复使用UIControl子类和IB中的设计

ios - UILabel 设置为隐藏时不隐藏

objective-c - iPad 键盘上的“完成”按钮和“最小化”按钮之间的区别

iphone - iOS:如何使用下载的 CSV 填充 CoreData

iphone - 为什么作者在下面的代码段中没有对childController做release呢?

android - iOS代码中如何使用j2objC进行转换?

iphone - 在下载完成之前播放视频

iphone - iOS : Custom button on Navigation Controller is only visible on 1 view controller and not on other View Controllers

iphone - 使用 Objective C 将文件读取/写入到 Windows Azure 存储