verificarse verificar verifica una sean que permitir permiso hasta estara esta empresarial disponible desarrollador dar confiar confiable como appvalley app aplicaciones ios iphone checkbox

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



verificar app ios (12)

Aquí está mi versión de checkbox para iphone.

Es clase única que extiende UIButton. Es simple, así que lo pegaré aquí.

Contenido del archivo CheckBoxButton.h

#import <UIKit/UIKit.h> @interface CheckBoxButton : UIButton @property(nonatomic,assign)IBInspectable BOOL isChecked; @end

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 imágenes para la propiedad marcada / no marcada, así como la propiedad isChecked, en el inspector de atributos de visual studio.

Para agregar CheckBoxButton en el guión gráfico o xib, simplemente agregue UIButton y configure la clase personalizada como en la imagen siguiente.

El botón enviará el evento UIControlEventValueChanged, cada vez que se cambie el estado de comprobación.

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?


El código de Everyones aquí es muy largo, ligeramente desordenado, y podría hacerse mucho más simple. Tengo un proyecto en GitHub que subclase UIControl que puede descargar y verificar, y le da un elemento de UI de casilla de verificación casi nativo:

https://github.com/Brayden/UICheckbox


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 /


Extendiendo la idea de Adrean , he logrado esto usando un enfoque muy simple.
Mi idea es cambiar el texto del botón (digamos checkBtn ) dependiendo de su estado, y luego cambiar el estado del botón en su IBAction .
A continuación está 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 } }


Lo hice con un UITextField para evitar dibujar algo extraño, pero me gustó poner dentro como texto el tic unicode (carácter Unicode ''CHECK MARK'' (U + 2713)) para el NSString: @ "/ u2713".

De esta manera, en mi archivo .h (implementando el protocolo para el UITextField ''UITextFieldDelegate''):

UITextField * myCheckBox;

En mi viewDidLoad o la función para 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! ...

Luego, agregue un selector de eventos para reencaminar en el evento táctil y llame al evento ''responseSelected'':

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

Finalmente responde a ese selector

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

La función ''isChecked'' solo verifica si el texto es la marca de verificación @ "/ u2713". Para evitar que se muestre el teclado cuando se selecciona el campo de texto, utilice el evento de UITextField ''textFieldShouldBeginEditing'' y agregue el selector de eventos para administrar la selección:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // Question selected form the checkbox [self checkboxSelected]; // Hide both keyboard and blinking cursor. return NO; }


Me gusta la idea de que Adrian use los personajes en lugar de las imágenes. Pero no me gusta el cuadro, solo necesita la marca de verificación (@ "/ u2713"). Dibujé un recuadro (una caja redondeada) programáticamente y coloqué un UILabel que contiene la marca de verificación dentro de él. Esta forma de implementación facilita el uso de la vista personalizada en cualquier aplicación sin importar ningún recurso dependiente. También puede personalizar el color de la marca de verificación, el cuadro redondeado 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]; } } }


Quería hacer esto programáticamente y también resolver el problema de que el área de impacto era demasiado pequeña. Esto es una adaptación de varias fuentes, incluyendo el comentarista de Mike y Mike, Agha.

En tu encabezado

@interface YourViewController : UIViewController { BOOL checkboxSelected; UIButton *checkboxButton; } @property BOOL checkboxSelected;; @property (nonatomic, retain) UIButton *checkboxButton; -(void)toggleButton:(id)sender;

Y en su implementación

// 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 pon este método también:

- (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]; }


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.


Subclase UIButton, suelte un botón para ver el controlador, selecciónelo y cambie el 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


en archivo .h

#import <UIKit/UIKit.h> @interface ViewController : UIViewController { BOOL isChecked; UIImageView * checkBoxIV; } @end

Y 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 hará el truco ...


esto también me está volviendo loco y encontré una solución diferente que funciona bien para mí y evita tener que usar imágenes.

  1. Agregue un nuevo objeto de etiqueta a Interface Builder.
  2. Cree una propiedad IBOutlet en Xcode y conéctela. En el siguiente código, lo llamé "totalmente pagado" porque quiero saber si alguien ha pagado por completo una suma de dinero.
  3. Agrega las 2 funciones a continuación. La función ''touchesBegan'' comprueba si tocó en algún lugar dentro del objeto de etiqueta ''fullyPaid'' y, si es así, llama a la función ''togglePaidStatus''. La función ''togglePaidStatus'' configura dos cadenas que tienen los caracteres Unicode que representan un cuadro vacío (/ u2610) y un recuadro marcado (/ u2611) respectivamente. Luego compara lo que está actualmente en el objeto ''fullyPaid'' y lo alterna con la otra cadena.

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

Obviamente, puede agregar controles adicionales para evitar que los usuarios alternen la casilla de verificación si la etiqueta no está habilitada, pero eso no se muestra 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]; }


usuario Aruna Lakmal; FYI, cuando agrega este código a IB como lo describe initWithFrame no se llama, initWithCoder es. Implemente initWithCoder y funcionará como usted describe.