Класс, производный от UIControl, и необходимо дважды вызвать drawRect, чтобы нарисовать правильное состояние элемента управления - PullRequest
1 голос
/ 16 января 2012

У меня есть класс, который наследует от UIControl, который обрабатывает touchEvents, и я не понимаю, почему метод setNeedsDisplay нужно дважды вызывать для touchEvents, чтобы в пользовательском интерфейсе отображалось правильное состояние. Я видел этот шаблон в нескольких примерах, где различные методы прикосновения [Began | Ended] все напрямую вызывают setNeedsDisplay, а затем снова с задержкой с помощью executeSelector.

Я вижу, каков результат, когда 2-й setNeedsDisplay не вызывается - элемент управления сначала отображается в выбранном состоянии, но не возвращается в нормальное состояние, поэтому фон остается выбранным.

Почему именно такое поведение происходит?

// a class that inherits from UIControl
- (void)drawRect:(CGRect)rect
{
    NSLog(@"drawRect, control state: %d", self.state);
    if (self.state == UIControlStateNormal)
    {
        [self setContentToNormalState];
        [self setBackgroundColor:[UIColor whiteColor]];
        NSLog(@"Set background color: White");
    }
    else 
    {
        [self setContentToSelectedState];
        [self setBackgroundColor:[UIColor lightGrayColor]];
        NSLog(@"Set background color: Grey");
    }

    [super drawRect:rect];
}

- (void)hesitateUpdate
{
    [self setNeedsDisplay];
}

#pragma mark - Touch event handling

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setHighlighted:YES];
    [self setNeedsDisplay];
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self setHighlighted:NO];    
    [super touchesMoved:touches withEvent:event];
//    [self setNeedsDisplay];    
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    [self setHighlighted:NO];

    [self setNeedsDisplay];
    [self performSelector:@selector(hesitateUpdate) withObject:nil afterDelay:0.1];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self setHighlighted:NO];

    [self setNeedsDisplay];
    // Even with the following, if I tap and hold momentarily in the simulator, 
    // sometimes, the control has the gray background instead of white at the end
    [self performSelector:@selector(hesitateUpdate) withObject:nil afterDelay:0.1];     
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...