0

我正在向 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];
    }
4

2 回答 2

2

的宽度可能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);

因为最后一个子视图总是决定下一个按钮的框架。

于 2013-08-07T22:59:18.353 回答
1

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

我也会在这里看看这条线:

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

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

NSLog(@"%@",NSStringFromCGPoint(topRight));
于 2013-08-07T22:40:01.597 回答