【问题标题】:How to determine which button was tapped?如何确定点击了哪个按钮?
【发布时间】:2012-03-30 20:18:11
【问题描述】:

我有这个日历,由以编程方式创建的 48 个帧组成...当我执行 UITapGestureRecognizer 时,它会返回帧的 x,y 坐标...知道如何确定哪个帧被点击了吗?

更新:这是创建框架的代码:

self.frame = frame;
self.backgroundColor = [UIColor colorWithRed:rd1 green:gr1 blue:bl1 alpha:1.0]; 
[[self layer] setBorderColor:[[UIColor blackColor] CGColor]]; 
[[self layer] setBorderWidth:0.5];  
[[self layer] setCornerRadius:10]; 
[self setClipsToBounds: YES];

【问题讨论】:

  • 您能否提供更多信息,例如你如何创建和布局你的 48 个按钮?例如,您可以遍历所有按钮并测试您的坐标是否属于按钮的框架,或者如果您知道布局规则,则可以根据坐标计算按钮...
  • 如果你有按钮,为什么不给每个按钮分配一个动作而不是手势识别器呢?

标签: cocoa-touch ios5 xcode4


【解决方案1】:

如果我了解您在做什么 - 那么下面的例程可能会有用。它获取触摸坐标,然后针对数组中的每个矩形对其进行测试。如果 CPPoint 在一个矩形内,那么你就有了索引号,并且基于它你可以做你需要做的事情。

根据您定义矩形数组的方式,您可能需要标准化触摸 CGPoint。

无论如何-希望它有所帮助。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view]; 

// See if the point touched is within these rectangular bounds
if (CGRectContainsPoint(self.gridRect, point))
{
    CGRect rect;
    int cnt = self.cellRectArray.count;
    for (int i = 0; i < cnt; i++) {

        rect = [[self.cellRectArray objectAtIndex:i] cellRect];
        rect = CGRectOffset(rect, self.gridOriginX, self.gridOriginY);
        rect = CGRectInset(rect, 10, 10);
        if (CGRectContainsPoint(rect, point)) {
            // do something
            break;
        }
    }
} 

}

【讨论】:

  • 我认为这会做到...我想我需要首先捕获每个矩形的坐标并将它们与其他数据(如日期等)一起存储在一个数组中。我'我会试一试并回复您...感谢您的回复!
  • 唯一棘手的事情是@在同一个坐标空间中工作:触摸坐标与 UIView 坐标。这就是CGRectOffset 的用途——相对于视图的 x/y 移动它们。 “cellRect”也是一个自定义的基于 NSObject 的类,用于将 CGRects 存储在 NSArray 中,因为您不能将原始 CGRects 存储在 NSArray 中。 - 干杯!
【解决方案2】:

如果你有按钮,如果你启用它们,点击它们会触发你链接到点击动作的方法。

因此每个按钮都有一个“标签”属性。

tag 属性可以让你知道哪个按钮触发了该方法。

编辑:

如果你的按钮属于UIButton类,你可以通过tag属性获取按钮的标签,即:

mybutton.tag

[mybutton tag]

【讨论】:

  • 您的代码没有按照 UIButton 类的含义创建 UIButton。见:developer.apple.com/library/ios/#documentation/uikit/reference/…
  • 我明白你在说什么......好吧,让我们改变它..我正在绘制一个矩形......我如何识别每个矩形(如 UIButton 中的“标签”) ?
  • myButton.tag = 1 , myOtherButton.tag = 2 等等。然后创建一个方法来链接他们的动作。看看我在之前的评论中发布的链接中给出的示例代码。您将了解如何使用 UIButton
  • 我不想使用 UIButton...我想在绘制矩形时使用它们...
【解决方案3】:

如果您使用的是UITapGestureRecognizer,那么为什么不直接询问它附加到哪个视图?

- (void)cellTapped:(UITapGestureRecognizer *)tapGestureRecognizer;
{
    NSLog(@"%@", tapGestureRecognizer.view);
}

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2014-06-21
    相关资源
    最近更新 更多