简体   繁体   中英

UIButtons overlapping

I want to make an app that has a view that moves randomly or moves at the location where you touch the screen. I have the following problem: i made a button that begins a random animations and i want to make another button that stops the animation. The problem is that the two buttons are overlapping and only the first one is shown at the location of the second one, I press it and the second one is shown at the location where is supposed to be. I don't know what i am doing wrong, probably i have some problem with the subviews. Here is the code where i draw the buttons.

- (void)drawRect:(CGRect)rect {
// Drawing code

UIButton *randomMovementButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[randomMovementButton addTarget:self 
           action:@selector(animationLoop:finished:context:)
 forControlEvents:UIControlEventTouchDown];
[randomMovementButton setTitle:@"Move Random" forState:UIControlStateNormal];
randomMovementButton.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self addSubview:randomMovementButton];

UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[stopButton addTarget:self
            action:@selector(stopAnimation:) 
     forControlEvents:UIControlEventTouchDown];
[randomMovementButton setTitle:@"Stop Moving Random" forState:UIControlStateNormal];
randomMovementButton.frame = CGRectMake(80.0, 210.0, 200.0, 40.0);
[self addSubview:stopButton];
}

Figured out my mistake, i was confused with the buttons' names and misused them.

只需为两个按钮使用不同的框架,它们就不会重叠...

They are not overlapping. The second button does not have a frame. You wrote this:

UIButton *stopButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[stopButton addTarget:self
        action:@selector(stopAnimation:) 
 forControlEvents:UIControlEventTouchDown];
[randomMovementButton setTitle:@"Stop Moving Random" forState:UIControlStateNormal];
randomMovementButton.frame = CGRectMake(80.0, 210.0, 200.0, 40.0);
[self addSubview:stopButton];

On the third and fourth line you wrote randomMovementButton instead of stopButton . This means both the Title and frame are set to the randomMovementButton and not the stopButton. Also, the frame on this second part and the first one are the same (Both are CGRectMake(80.0, 210.0, 200.0, 40.0) ) which will make them overlap when you fix it. Change one of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM