Casilla de verificación en la aplicación de iOS

votos
34

Necesito agregar controles de casilla de verificación a mi formulario. Sé que no hay tal control en iOS SDK. ¿Cómo podría hacer esto?

Publicado el 16/03/2009 a las 13:05
fuente por usuario
En otros idiomas...                            


13 respuestas

votos
31

esto ha sido volviendo loco también y he encontrado una solución diferente que funciona bien para mí y evita tener que utilizar las imágenes.

  1. Añadir un nuevo objeto etiqueta para el Interface Builder.
  2. Crear una propiedad IBOutlet en Xcode y conectarlo a la altura. En el código de abajo he llamado 'fullyPaid' como yo quiero saber si alguien ha pagado la totalidad de una suma de dinero.
  3. Añadir las 2 funciones a continuación. La función comprueba 'touchesBegan' si tocaban en algún lugar dentro del objeto etiqueta 'fullyPaid' y si es así, se llama a la función 'togglePaidStatus'. La función 'togglePaidStatus' establece dos cadenas que tienen los caracteres Unicode que representan una caja vacía (\ u2610) y una casilla marcada (\ u2611), respectivamente. A continuación, se compara lo que está actualmente en el objeto 'fullyPaid' y se alterna con la otra cadena.

Es posible que desee llamar a la función togglePaidStatus en la función viewDidLoad para establecerlo en una cadena vacía inicialmente.

Obviamente se puede añadir controles adicionales para evitar que los usuarios clickeando en la casilla si la etiqueta no está habilitado, pero eso no es mostrado a continuación.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];   
    if (CGRectContainsPoint([fullyPaid frame], [touch locationInView:self.view]))
    {
        [self togglePaidStatus];
    }
}
-(void) togglePaidStatus
{
    NSString *untickedBoxStr = [[NSString alloc] initWithString:@"\u2610"];
    NSString *tickedBoxStr = [[NSString alloc] initWithString:@"\u2611"];   

    if ([fullyPaid.text isEqualToString:tickedBoxStr])
    {
        fullyPaid.text = untickedBoxStr;
    }
    else
    {
        fullyPaid.text = tickedBoxStr;
    }

    [tickedBoxStr release];
    [untickedBoxStr release];
}
Respondida el 10/04/2010 a las 22:23
fuente por usuario

votos
26

En general, usaría el UISwitch para la funcionalidad tipo casilla de verificación.

Sin embargo, podría hacer su propio rollo usando un control de imagen con dos imágenes (marcadas / desmarcadas) y cambiando las imágenes cuando toquen el control /

Respondida el 16/03/2009 a las 13:12
fuente por usuario

votos
10

Si muestra un grupo de opciones y el usuario puede seleccionar una de ellas, use una vista de tabla con un accesorio de marca de verificación y un color de texto diferente en la fila seleccionada.

Si tiene una opción única, su mejor opción es usar un interruptor. Si no puede o no quiere, use un botón, establezca la imagen normal en un cuadro vacío y la imagen seleccionada en un cuadro marcado. Tendrá que hacer esas dos imágenes usted mismo o buscar gráficos comunes para usar.

Respondida el 16/03/2009 a las 13:33
fuente por usuario

votos
8

La extensión a la idea de Adrean , que he logrado esto con un enfoque muy simple.
Mi idea es botón para cambiar (digamos checkBtn) de texto, dependiendo de su estado, y luego cambiar el estado de botón en su IBAction.
A continuación se muestra el código de cómo hice esto:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [checkBtn setTitle:@"\u2610" forState:UIControlStateNormal];    // uncheck the button in normal state
    [checkBtn setTitle:@"\u2611" forState:UIControlStateSelected];  // check the button in selected state
}

- (IBAction)checkButtonTapped:(UIButton*)sender {
    sender.selected = !sender.selected;    // toggle button's selected state  

    if (sender.state == UIControlStateSelected) {    
        // do something when button is checked 
    } else {
        // do something when button is unchecked
    }
}
Respondida el 19/03/2014 a las 05:17
fuente por usuario

votos
6

Aquí está mi versión de la casilla de verificación para el iphone.

Es clase única que se extiende UIButton. Es simple así que voy a pegar aquí.

el contenido del archivo CheckBoxButton.h

#import <UIKit/UIKit.h>

@interface CheckBoxButton : UIButton

@property(nonatomic,assign)IBInspectable BOOL isChecked;

@end

el contenido del archivo CheckBoxButton.m

#import "CheckBoxButton.h"

@interface CheckBoxButton()

@property(nonatomic,strong)IBInspectable UIImage* checkedStateImage;
@property(nonatomic,strong)IBInspectable UIImage* uncheckedStateImage;

@end

@implementation CheckBoxButton

-(id)init
{
    self = [super init];

    if(self)
    {
        [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside];
    }

    return self;
}

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if(self)
    {
        [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside];
    }

    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if(self)
    {
        [self addTarget:self action:@selector(switchState) forControlEvents:UIControlEventTouchUpInside];
    }

    return self;
}

-(void)setIsChecked:(BOOL)isChecked
{
    _isChecked = isChecked;

    if(isChecked)
    {
        [self setImage:self.checkedStateImage forState:UIControlStateNormal];
    }
    else
    {
        [self setImage:self.uncheckedStateImage forState:UIControlStateNormal];
    }
}

-(void)switchState
{
    self.isChecked = !self.isChecked;
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

@end

Puede establecer las imágenes de la propiedad comprobados y / o sin control, así como isChecked en el inspector de atributos de Visual Studio.

introducir descripción de la imagen aquí

Para añadir CheckBoxButton de guión gráfico o xib, simple UIButton agregar y configurar clase personalizada como en la imagen siguiente.

introducir descripción de la imagen aquí

Botón enviará evento UIControlEventValueChanged, cada vez que se cambia el estado isChecked.

Respondida el 31/12/2014 a las 13:44
fuente por usuario

votos
6

Yo quería hacer esto mediante programación, y también resolver el problema de que la zona más afectada fue realmente demasiado pequeño. Esta es una adaptación de varias fuentes, incluyendo Mike y comentarista de Mike Agha.

En su cabecera

@interface YourViewController : UIViewController {
    BOOL checkboxSelected;
    UIButton *checkboxButton;
}

@property BOOL checkboxSelected;;
@property (nonatomic, retain) UIButton *checkboxButton;

-(void)toggleButton:(id)sender;

Y en su puesta en práctica

// put this in your viewDidLoad method. if you put it somewhere else, you'll probably have to change the self.view to something else
// create the checkbox. the width and height are larger than actual image, because we are creating the hit area which also covers the label
UIButton* checkBox = [[UIButton alloc] initWithFrame:CGRectMake(100, 60,120, 44)];  
[checkBox setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
// uncomment below to see the hit area
// [checkBox setBackgroundColor:[UIColor redColor]];
[checkBox addTarget:self action:@selector(toggleButton:) forControlEvents: UIControlEventTouchUpInside];
// make the button's image flush left, and then push the image 20px left
[checkBox setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[checkBox setImageEdgeInsets:UIEdgeInsetsMake(0.0, 20.0, 0.0, 0.0)];
[self.view addSubview:checkBox];

// add checkbox text text
UILabel *checkBoxLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 74,200, 16)];
[checkBoxLabel setFont:[UIFont boldSystemFontOfSize:14]];
[checkBoxLabel setTextColor:[UIColor whiteColor]];
[checkBoxLabel setBackgroundColor:[UIColor clearColor]];
[checkBoxLabel setText:@"Checkbox"];
[self.view addSubview:checkBox];

// release the buttons
[checkBox release];
[checkBoxLabel release];

Y poner este método en demasiado:

- (void)toggleButton: (id) sender
{
    checkboxSelected = !checkboxSelected;
    UIButton* check = (UIButton*) sender;
    if (checkboxSelected == NO)
        [check setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
    else
        [check setImage:[UIImage imageNamed:@"checkbox-checked.png"] forState:UIControlStateNormal];

}
Respondida el 21/05/2010 a las 17:46
fuente por usuario

votos
4

Everyones código aquí es muy largo, un poco desordenado, y se podría hacer mucho más simple. Tengo un proyecto en GitHub esa subclase uicontrol que se puede descargar y echa un vistazo y le da un elemento de interfaz de usuario casilla casi nativa:

https://github.com/Brayden/UICheckbox

Respondida el 18/07/2012 a las 08:03
fuente por usuario

votos
1

UIButton subclase, la caída de un botón para ver controlador, seleccionarlo y cambiar nombre de la clase a CheckBox en el inspector de identidad.

#import "CheckBox.h"

@implementation CheckBox

#define checked_icon @"checked_box_icon.png"
#define empty_icon @"empty_box_icon.png"

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self setImage:[UIImage imageNamed:empty_icon] forState:UIControlStateNormal];
        [self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

- (void)didTouchButton {
    selected = !selected;
    if (selected)
        [self setImage:[UIImage imageNamed:checked_icon] forState:UIControlStateNormal];
    else
        [self setImage:[UIImage imageNamed:empty_icon] forState:UIControlStateNormal];
}

@end
Respondida el 13/05/2015 a las 11:59
fuente por usuario

votos
1

Lo hice con un UITextField evitar llamar la nada extraño, pero me ha gustado poner en el interior como texto Unicode la garrapata (caracteres Unicode 'Marca de verificación' (U + 2713)) para el NSString: @ "\ u2713".

De esta manera, en mi archivo .h (aplicación del protocolo para 'UITextFieldDelegate' la UITextField):

UITextField * myCheckBox;

En mi viewDidLoad o la función de preparar la interfaz de usuario:

...
myCheckBox = [[UITextField alloc] initWithFrame:aFrame];
myCheckBox.borderStyle = UITextBorderStyleRoundedRect; // System look like
myCheckBox.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
myCheckBox.textAlignment = NSTextAlignmentLeft;
myCheckBox.delegate = self;
myCheckBox.text = @" -"; // Initial text of the checkbox... editable!
...

A continuación, añadir un selector de sucesos para rear en el caso del tacto y llamando evento 'responseSelected':

...
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkboxSelected)];
[myCheckBox addGestureRecognizer:tapGesture];
...

Finalmente responder a ese selector

-(void) checkboxSelected
{
    if ([self isChecked])
    {
        // Uncheck the selection
        myCheckBox.text = @" -";
    }else{
       //Check the selection
       myCheckBox.text = @"\u2713";
    }
}

La función 'isChecked' sólo comprueba si el texto es la marca de verificación "\ u2713" @. Para evitar que muestra el teclado cuando se selecciona el campo de texto utilizar el evento de 'textFieldShouldBeginEditing' la UITextField y poner el selector de eventos para gestionar la selección:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    // Question selected form the checkbox
    [self checkboxSelected];

    // Hide both keyboard and blinking cursor.
    return NO;
}
Respondida el 07/10/2014 a las 12:13
fuente por usuario

votos
1

en el archivo .h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    BOOL isChecked;
    UIImageView * checkBoxIV;
}
@end

Y el archivo .m

- (void)viewDidLoad
{
    [super viewDidLoad];
    isChecked = NO;

    //change this property according to your need
    checkBoxIV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 15, 15)]; 
    checkBoxIV.image =[UIImage imageNamed:@"checkbox_unchecked.png"]; 

    checkBoxIV.userInteractionEnabled = YES;
    UITapGestureRecognizer *checkBoxIVTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlecheckBoxIVTapGestureTap:)];
    checkBoxIVTapGesture.numberOfTapsRequired = 1;
    [checkBoxIV addGestureRecognizer:checkBoxIVTapGesture];
}

- (void)handlecheckBoxIVTapGestureTap:(UITapGestureRecognizer *)recognizer {
    if (isChecked) {
        isChecked = NO;
        checkBoxIV.image =[UIImage imageNamed:@"checkbox_unchecked.png"];
    }else{
        isChecked = YES;
        checkBoxIV.image =[UIImage imageNamed:@"checkbox_checked.png"];   
    }
}

Esto va a hacer el truco ...

Respondida el 14/06/2013 a las 11:12
fuente por usuario

votos
1

Me gusta la idea de Adrian utilizar los caracteres en lugar de imágenes. Pero no me gusta la caja, que sólo necesita la marca de verificación en sí (@ "\ u2713"). Dibujo un cuadro (una caja redondeada) mediante programación y colocar un UILabel contiene la marca de verificación en su interior. Esta forma de ejecución hace que sea fácil de usar la vista personalizada en cualquier aplicación sin cuidado acerca de cualquier recurso dependiente. También puede personalizar el color de la marca de verificación, la caja redondeada y el fondo con facilidad. Aquí está el código completo:

#import <UIKit/UIKit.h>

@class CheckBoxView;

@protocol CheckBoxViewDelegate
- (void) checkBoxValueChanged:(CheckBoxView *) cview;
@end

@interface CheckBoxView : UIView {
    UILabel *checkMark;
    bool isOn;
    UIColor *color;
    NSObject<CheckBoxViewDelegate> *delegate;
}
@property(readonly) bool isOn;
@property(assign) NSObject<CheckBoxViewDelegate> *delegate;

- (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef) context;
@end



#import "CheckBoxView.h"

#define SIZE 30.0
#define STROKE_WIDTH 2.0
#define ALPHA .6
#define RADIUS 5.0

@implementation CheckBoxView
@synthesize isOn, delegate;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, SIZE, SIZE)])) {
        // Initialization code
    }
    //UIColor *color = [UIColor blackColor];
    color = [[UIColor alloc] initWithWhite:.0 alpha:ALPHA];

    self.backgroundColor = [UIColor clearColor];
    checkMark = [[UILabel alloc] initWithFrame:CGRectMake(STROKE_WIDTH, STROKE_WIDTH, SIZE - 2 * STROKE_WIDTH, SIZE - 2*STROKE_WIDTH)];
    checkMark.font = [UIFont systemFontOfSize:25.];
    checkMark.text = @"\u2713";
    checkMark.backgroundColor = [UIColor clearColor];
    checkMark.textAlignment = UITextAlignmentCenter;
    //checkMark.textColor = [UIColor redColor];
    [self addSubview:checkMark];
    [checkMark setHidden:TRUE];
    isOn = FALSE;
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGRect _rect = CGRectMake(STROKE_WIDTH, STROKE_WIDTH, SIZE - 2 * STROKE_WIDTH, SIZE - 2*STROKE_WIDTH);
    [self drawRoundedRect:_rect inContext:UIGraphicsGetCurrentContext()];
    [checkMark setHidden:!isOn];
}


- (void)dealloc {
    [checkMark release];
    [color release];
    [super dealloc];
}

- (void) drawRoundedRect:(CGRect) rect inContext:(CGContextRef) context{
    CGContextBeginPath(context);
    CGContextSetLineWidth(context, STROKE_WIDTH);
    CGContextSetStrokeColorWithColor(context, [color CGColor]);
    CGContextMoveToPoint(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMinY(rect));
    CGContextAddArc(context, CGRectGetMaxX(rect) - RADIUS, CGRectGetMinY(rect) + RADIUS, RADIUS, 3 * M_PI / 2, 0, 0);
    CGContextAddArc(context, CGRectGetMaxX(rect) - RADIUS, CGRectGetMaxY(rect) - RADIUS, RADIUS, 0, M_PI / 2, 0);
    CGContextAddArc(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMaxY(rect) - RADIUS, RADIUS, M_PI / 2, M_PI, 0);
    CGContextAddArc(context, CGRectGetMinX(rect) + RADIUS, CGRectGetMinY(rect) + RADIUS, RADIUS, M_PI, 3 * M_PI / 2, 0);
    CGContextClosePath(context);
    CGContextStrokePath(context);
}

#pragma mark Touch
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint loc = [touch locationInView:self];
    if(CGRectContainsPoint(self.bounds, loc)){
        isOn = !isOn;
        //[self setNeedsDisplay];
        [checkMark setHidden:!isOn];
        if([delegate respondsToSelector:@selector(checkBoxValueChanged:)]){
            [delegate checkBoxValueChanged:self];
        }
    }
}
Respondida el 23/07/2010 a las 10:41
fuente por usuario

votos
0

Hice un poco. Libre para adquirir de GitHub. A ver si esto le ayudará. El efecto es como

introducir descripción de la imagen aquí

Respondida el 01/04/2019 a las 20:36
fuente por usuario

votos
0

usuario Aruna Lakmal; Para su información, cuando se agrega este código al IB como usted la describe initWithFrame no se llama, es initWithCoder. Implementar initWithCoder y funcionará como usted la describe.

Respondida el 20/01/2013 a las 04:15
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more