2010-06-01 22 views
41

He hecho un custom UISwitch (from this post). Pero el problema es que mis textos personalizados son un poco largos. ¿Hay alguna manera de cambiar el tamaño del interruptor? [Probé setBounds, no funcionó]¿Cómo cambiar el tamaño de un UISwitch?

Editar:

Aquí está el código que utilicé:

@interface CustomUISwitch : UISwitch  
- (void) setLeftLabelText: (NSString *) labelText; 
- (void) setRightLabelText: (NSString *) labelText;  
@end 

@implementation CustomUISwitch 

- (UIView *) slider 
{ 
    return [[self subviews] lastObject]; 
} 
- (UIView *) textHolder 
{ 
    return [[[self slider] subviews] objectAtIndex:2]; 
} 
- (UILabel *) leftLabel 
{ 
    return [[[self textHolder] subviews] objectAtIndex:0]; 
} 
- (UILabel *) rightLabel 
{ 
    return [[[self textHolder] subviews] objectAtIndex:1]; 
} 
- (void) setLeftLabelText: (NSString *) labelText 
{ 
    [[self leftLabel] setText:labelText]; 
} 
- (void) setRightLabelText: (NSString *) labelText 
{ 
    [[self rightLabel] setText:labelText]; 
} 
@end 

mySwitch = [[CustomUISwitch alloc] initWithFrame:CGRectZero]; 

//Tried these, but did not work 
//CGRect aFrame = mySwitch.frame; 
//aFrame.size.width = 200; 
//aFrame.size.height = 100; 
//mySwitch.frame = aFrame; 

[mySwitch setLeftLabelText: @"longValue1"]; 
[mySwitch setRightLabelText: @"longValue2"]; 
+0

¿Está utilizando UISwitch (del sujeto) o UICustomSwitch (de su enlace)? La [clase UICustomSwitch] (http://www.catamount.com/blog/?p=1063) es en realidad un UISlider. – progrmr

+0

pero hereda UISwitch, ¿cómo puede ser un control deslizante? – mshsayem

+0

UICustomSwitch hereda de UISlider. Cual estas usando? Su código dice CustomUISwitch, su sujeto dice UISwitch, pero el enlace que dio apunta a una implementación UICustomSwitch? ¡No podemos responder a su pregunta muy bien a menos que usted diga cuál de los 3 realmente quiso decir! – progrmr

Respuesta

162

La forma más sencilla es cambiar su tamaño, como una vista:

UISwitch *mySwitch = [[UISwitch alloc] init]; 
mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75); 

y usted no tiene que preocuparse por nada más!

+4

¡Esta es la solución más simple y limpia! +1 –

+0

¿No funciona? – KaiserJohaan

+1

El problema es que cuando hacemos esto, pixela el interruptor ... ¿De cualquier otra manera? – TheTiger

7

Muchos controles están destinados a ser de un tamaño específico. Si estuviera implementando esto usted mismo, anularía setFrame:, ajuste el parámetro de cuadro para que coincida con el tamaño requerido de su control, y luego páselo a [super setFrame:].

Si subclasifica un control que tiene este comportamiento, realmente no hay forma de anularlo porque su subclase heredará la implementación de la superclase de setFrame:, que modifica el rectángulo de su marco. Y no hay forma de establecer el marco de su control sin llamar al [super setFrame:].

Es muy probable que tenga que heredar de UIControl e implemente manualmente las propiedades/comportamientos que desee desde UISwitch para solucionar esto.

+0

Pensé que ... – mshsayem

+1

Confirmado. Fui a UISwitch.h ... tiene este comentario en initWithFrame: "// Esta clase impone un tamaño apropiado para el control. El tamaño del fotograma se ignora." – mshsayem

3

UISwitch no está diseñado para personalizarse.

Creo que la mejor solución es descargar una de las implementaciones de conmutadores personalizadas mencionadas en la otra pregunta a la que hace referencia. O bien UICustomSwitch o RCSwitch. Ambos deberían ser capaces de manejar etiquetas anchas.

+0

He usado UICustomSwitch aquí ... pero no puedo cambiar el tamaño ... Etiquetas largas se envuelven .. RCSwitch funciona ... gracias – mshsayem

3

No hay ninguna opción para cambiar el tamaño uiswitch en xib, por lo que necesita para crear y cambiar su tamaño en la clase del controlador,

 UISwitch *onoff = [[UISwitch alloc] initWithFrame: CGRectMake(0, 0, 10, 10)]; 
    onoff.transform = CGAffineTransformMakeScale(0.50, 0.50); 
    [self.view addSubview:onoff]; 
1

Aquí es una solución de código:

UISwitch *mySwitchNewsletter = [[UISwitch alloc] initWithFrame: CGRectMake(varSettingsSwitchNewsletter_x, 
                      varSettingsSwitchNewsletter_y, 
                      varSettingsSwitchNewsletter_width, 
                      varSettingsSwitchNewsletter_height)]; 
if (mySwitchNewsletter != nil) { 

    [varCommerceSettingsView addSubview:mySwitchNewsletter]; 


    float mySwitchScaleFactor = (varSettingsSwitchNewsletter_scale/100.0); 


    CGFloat dX=mySwitchNewsletter.bounds.size.width/2, dY=mySwitchNewsletter.bounds.size.height/2; 
    mySwitchNewsletter.transform = CGAffineTransformTranslate(CGAffineTransformScale(CGAffineTransformMakeTranslation(-dX, -dY), mySwitchScaleFactor, mySwitchScaleFactor), dX, dY); 

    mySwitchNewsletter release]; 
} 

Dónde varSettingsSwitchNewsletter_scale es una int de 0 a 100 (%).

2

Si desea cambiar el tamaño del interruptor puesto a través del guión gráfico o en punta, Usted puede subclase UISwitch y reemplazar el método awakeFromNib:

- (void)awakeFromNib { 
    self.transform = CGAffineTransformMakeScale(0.75, 0.75); 
} 

Seleccione el control del interruptor y cambiar su clase a su clase de interruptor de encargo.

enter image description here

0
// Just in case someone trying to hard code UISwitch in Xcode 6.4 the following is working 
// in .h 
@property UISwitch * onoff; 

// in .m 

self.onoff = [[UISwitch alloc] initWithFrame:CGRectMake(160, 40, 0, 0)]; 
_onoff.transform = CGAffineTransformMakeScale(0.50, 0.50); 
[self.view addSubview:self.onoff]; 
11

Aquí está la versión 3 de rápida respuesta mxg:

let mySwitch = UISwitch() 
mySwitch.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) 
Cuestiones relacionadas