【问题标题】:Getting the Tag Number of Touched Object获取触摸对象的标签号
【发布时间】:2013-04-12 23:09:38
【问题描述】:

我有一个按钮。每次用户点击它时,应用程序都会实例化 UIImageView (imageview),为其标签分配一个唯一编号。

- (IBAction)buttonClicked:(id)sender {
    imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 240)];
    NSUInteger currentag = [self UniqueNum]; // Assigning a unique number to the tag variable
    [self.view addSubview:imageview];
    imageview.backgroundColor = [UIColor blueColor];
    imageview.userInteractionEnabled = YES;
    imageview.tag = currentag;
}

我的目标是获取用户触摸的 UIImageView 副本的标签号。使用下面的代码,我实际得到的是应用程序最后创建的 UIImageView 副本的标签号。如何改进它以便应用程序指向被触摸对象的标签号?

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view] == imageview) {
        NSLog(@"Tag: %i",imageview.tag);
    }    
}

感谢您的帮助。

【问题讨论】:

    标签: ios6 tags addsubview


    【解决方案1】:

    如果您需要交互,我建议在这里使用带有自定义图像的 UIButtons 而不是 UIImageViews。

    添加按钮时添加:

       [imageview addTarget:self action:@selector(someMethod:) forControlEvents:UIControlEventAllTouchEvents]; 
    

    然后只需将 sender 中的 someMethod(您的声明)转换为 UIView 以获取其标签。

    顺便说一句,someMethod 的方法签名是这样的:

    -(void) someMethod:(id)sender
    

    您还可以选择添加事件参数,但这里似乎不需要。

    【讨论】:

    • 啊……这很聪明。让我看看。谢谢。
    • 嗯...我在“imageview”上收到一条错误消息,上面写着“'UIImageView' 没有可见的@interface 声明选择器'addTarget:action:forControlEvents'。”
    • @TBlue Damnit,忘了这仅适用于从 UIControl 继承的类的实例。如果您仍想使用此方法,请将 UIImageViews 更改为 UIButtons 并设置图像。
    • 是的。我刚刚发现我只能用 UIButton 来做到这一点。
    • 好的。我想我可以为 UIImageView 使用 UIPanGestureRecognizer。
    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多