UIButton仅检测上半部分的触摸

时间:2013-08-07 22:31:16

标签: ios objective-c uibutton touches

我正在向UIView添加3个UIButton,通常只有1到2个会检测到触摸,即使这样,它也只会检测到它们的上半部分。有人知道为什么会这样吗?

for (int i = 0; i <= 2; i++) {
        int randIndex = arc4random() % [images count];
      //  UIImage *randImage = [images objectAtIndex:randIndex];
        NSString *number = [numbers objectAtIndex:randIndex];
        [images removeObjectAtIndex:randIndex];
        [numbers removeObjectAtIndex:randIndex];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      //  [button setImage:randImage forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpOutside];
        button.frame = CGRectMake(0, 8, 108, 40);
        button.tag = [number integerValue];
        for (UIView *sub in [baseone subviews]) {
            CGPoint topRight = CGPointMake(sub.frame.origin.x + sub.frame.size.width, sub.frame.origin.y);
            button.frame = CGRectMake(topRight.x, 8, 108, 40);
        }
        [baseone addSubview:button];
    }

2 个答案:

答案 0 :(得分:1)

您的按钮很可能彼此重叠,或者可能存在重叠的视图。

我还想看看这一行:

CGPoint topRight = CGPointMake(sub.frame.origin.x + sub.frame.size.width, sub.frame.origin.y);

我建议记录CGPoint值以确保按钮位置正确:

NSLog(@"%@",NSStringFromCGPoint(topRight));

答案 1 :(得分:1)

baseone的宽度可能只大到足以包含前两个按钮。你看到第三个按钮的触地选择吗?

另外,您的控制事件是TouchUpOutside,我经常看到TouchUpInside,是故意的吗?

PS无法解决您的问题,但这个循环:

for (UIView *sub in [baseone subviews]) {
       CGPoint topRight = CGPointMake(sub.frame.origin.x + sub.frame.size.width,    sub.frame.origin.y);
       button.frame = CGRectMake(topRight.x, 8, 108, 40);
}

可以简化为:

UIView * sub = [[baseone subviews] lastObject]
button.frame = CGRectMake(sub.frame.origin.x+sub.frame.size.width, 8, 108, 40);

因为最后一个子视图总是确定下一个按钮的帧。