user2272641
user2272641

Reputation: 131

UIButton only detects touches on top half

I am adding 3 UIButtons to a UIView, and usually only 1 to 2 of them will detect touches, and even then it will only be the top half of the buttons the detect them. Anyone know why this would happen?

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];
    }

Upvotes: 0

Views: 456

Answers (2)

thelaws
thelaws

Reputation: 8001

It's possible that baseone's width is only large enough to contain the first two buttons. Do you see the touch down selection of the third button?

Also, your control event is TouchUpOutside, I've usually seen TouchUpInside, was that intentional?

PS Doesn't solve your problem, but this loop:

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);
}

can be simplified to:

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

since the last subview always determines the frame of the next button.

Upvotes: 2

dana0550
dana0550

Reputation: 1125

Most likely your buttons are overlapping each other or there could be overlapping views.

I would also take a look at this line here:

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

I would suggest logging the CGPoint Value to make sure the button location is correct:

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

Upvotes: 1

Related Questions