2010-05-24 9 views
7

Cómo configurar el control deslizante para hacer clic en la posición y obtener el valor del control deslizante en la ubicación clicada en UISlider en la programación de iPhone. Sé que podemos arrastrar el control deslizante a esa posición, pero no quiero hacerlo. ¿Puedes decirme cómo configurar el control deslizante para hacer clic en la posición? ¿Es posible hacer esto?iPhone: Programar UISlider para colocarlo en la ubicación clicada

Respuesta

7

Puede simplemente agregar un UITAPGestureRecognizer al control deslizante, luego extraer el UIEvent y los toques asociados con él para descubrir a lo largo del UISlider que se realizó el tap. Luego, configure el valor de su control deslizante en este valor calculado.

ACTUALIZACIÓN:

En primer lugar, la configuración de su deslizador y añadir el reconocedor gesto a ella.

UISlider *slider = [[[UISlider alloc] init] autorelease]; 
… 
<slider setup> 
… 
UITapGestureRecognizer *gr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)] autorelease]; 
[slider addGestureRecognizer:gr]; 

luego implementar el selector

- (void)sliderTapped:(UIGestureRecognizer *)gestureRecognizer { 
    <left as a user excercise*> 
} 

* Consejo: Read the docs de averiguar cómo obtener el locationInView extrapola y averiguar lo que el regulador debe ser

+0

le puede dar una idea aproximada de cómo introducir UITapGestureRecognizer en deslizador? – suse

19

Aquí está la parte "izquierda como un ejercicio de usuario ":

- (void) tapped: (UITapGestureRecognizer*) g { 
    UISlider* s = (UISlider*)g.view; 
    if (s.highlighted) 
     return; // tap on thumb, let slider deal with it 
    CGPoint pt = [g locationInView: s]; 
    CGFloat percentage = pt.x/s.bounds.size.width; 
    CGFloat delta = percentage * (s.maximumValue - s.minimumValue); 
    CGFloat value = s.minimumValue + delta; 
    [s setValue:value animated:YES]; 
} 
11

La forma en que lo hice es para subclasificar el deslizador y cheque en touchesBegan. Si el usuario pulsa sobre el área de botón para el pulgar (que rastreamos) y luego ignorar el grifo, pero en ningún otro lugar en la barra de seguimiento que hacemos: :

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint touchLocation = [touch locationInView:self]; 

    // if we didn't tap on the thumb button then we set the value based on tap location 
    if (!CGRectContainsPoint(lastKnownThumbRect, touchLocation)) { 

     self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x/self.frame.size.width); 
    } 

    [super touchesBegan:touches withEvent:event]; 
} 

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value { 

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value]; 
    lastKnownThumbRect = thumbRect; 
    return thumbRect; 
} 
+1

mejor solución –

+1

si usó una imagen -setThumb personalizada, use 'self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * ((touchLocation.x - self.currentThumbImage.size.width/2)/(self.frame.size.width-self.currentThumbImage.size.width)); 'in -touchesBegan. – SwiftArchitect

1

que estaba usando el código UISlider subclases para escuchar eventos valueChanged en ios6> para implementar un tipo de función de ajuste a cuadrícula.

Esto no funcionaba cuando se actualizó a iOS7 porque ya no activa el UIControlEventsValueChanged. Para cualquier persona que tenga el mismo problema que se fija mediante la adición de una línea en el caso de() de la siguiente manera:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint touchLocation = [touch locationInView:self]; 

    // if we didn't tap on the thumb button then we set the value based on tap location 
    if (!CGRectContainsPoint(lastKnownThumbRect, touchLocation)) { 

     self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x/self.frame.size.width); 
     [self sendActionsForControlEvents:UIControlEventValueChanged]; 
    } 

    [super touchesBegan:touches withEvent:event]; 
} 

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value { 

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value]; 
    lastKnownThumbRect = thumbRect; 
    return thumbRect; 
} 

espero que ayude a alguien :)

0

he utilizado este código. Obtener de: http://imagineric.ericd.net/2012/11/15/uislider-touch-to-set-value/

UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sliderTapped:)]; 
[slider addGestureRecognizer:gr]; 



- (void)sliderTapped:(UIGestureRecognizer *)g { 
     UISlider* s = (UISlider*)g.view; 
     if (s.highlighted) 
      return; // tap on thumb, let slider deal with it 
     CGPoint pt = [g locationInView: s]; 
     CGFloat percentage = pt.x/s.bounds.size.width; 
     CGFloat delta = percentage * (s.maximumValue - s.minimumValue); 
     CGFloat value = s.minimumValue + delta; 
     [s setValue:value animated:YES]; 
    } 

Espero que esto pueda ayudarlo.

0

Parece que solo subclasificar UISlider y volver siempre fiel a beginTracking produce el efecto deseado.

IOS 10 y Swift 3

class CustomSlider: UISlider { 
    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { 
     return true 
    } 
} 
Cuestiones relacionadas