Ho bisogno di aggiungere controlli caselle di controllo alla mia forma. So che non esiste il controllo in iOS SDK. Come potrei fare questo?
Casella di controllo in applicazione iOS
questo è stato facendo impazzire troppo e ho trovato una soluzione diversa che funziona bene per me ed evita di dover utilizzare le immagini.
- Aggiungere un nuovo oggetto etichetta Interface Builder.
- Creare una proprietà IBOutlet in Xcode e collegarlo fino ad esso. Nel codice di seguito l'ho chiamata 'fullyPaid' come voglio sapere se qualcuno ha interamente versato una somma di denaro.
- Aggiungere le 2 funzioni di seguito. Controlli La funzione 'touchesBegan' se toccato da qualche parte dentro oggetto l'etichetta 'fullyPaid' ed in caso affermativo, si chiama la funzione 'togglePaidStatus'. La funzione 'togglePaidStatus' imposta due stringhe aventi i caratteri unicode rappresentano una scatola vuota (\ u2610) e una casella selezionata (\ u2611) rispettivamente. Poi si confronta ciò che è attualmente in oggetto la 'fullyPaid' e alterna con l'altra stringa.
Si potrebbe desiderare di chiamare la funzione togglePaidStatus nella funzione viewDidLoad per impostarla su una stringa vuota inizialmente.
Ovviamente è possibile aggiungere ulteriori controlli per impedire agli utenti non girevoli la casella di controllo se l'etichetta non è abilitato, ma non è indicato di seguito.
-(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];
}
In generale, si può usare l'UISwitch per la funzionalità di casella di controllo simile.
Si potrebbe rotolare il proprio se utilizzando un controllo immagine con due immagini (controllato / incontrollato) e la commutazione delle immagini quando toccano il controllo /
Se si sta mostrando un gruppo di opzioni e l'utente può selezionare uno di loro, utilizzare un Tableview con un accessorio segno di spunta e un diverso colore del testo sulla riga selezionata.
Se si dispone di una sola opzione, la soluzione migliore è quella di utilizzare un interruttore. Se non si può o non si vuole, utilizzare un pulsante, impostando l'immagine normale ad una scatola vuota e l'immagine selezionata in una casella selezionata. Dovrete fare quelle due immagini da soli o trovare grafica stock da utilizzare per loro.
L'estensione per l'idea di Adrean , ho realizzato questo usando un approccio molto semplice.
La mia idea è pulsante per cambiare (diciamo checkBtn) il testo a seconda del suo stato, e quindi modificare lo stato del pulsante nella sua IBAction.
Di seguito è riportato il codice come ho fatto questo:
- (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
}
}
Ecco la mia versione di casella di controllo per iPhone.
È classe singola che si estende UIButton. E 'semplice quindi mi incollarlo qui.
contenuto del file CheckBoxButton.h
#import <UIKit/UIKit.h>
@interface CheckBoxButton : UIButton
@property(nonatomic,assign)IBInspectable BOOL isChecked;
@end
contenuto del file 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
È possibile impostare le immagini per controllare / incontrollato e IsChecked proprietà nell'attributo ispettore di Visual Studio.

Per aggiungere CheckBoxButton in storyboard o XI ter, semplice UIButton aggiungere e configurare classe personalizzata come immagine successiva su.

Pulsante invierà evento UIControlEventValueChanged, ogni volta quando lo stato IsChecked è cambiato.
Ho voluto fare questo a livello di codice, e anche risolvere il problema che ha colpito la zona era davvero troppo piccolo. Questo è adattato da varie fonti, tra cui Mike e commentatore di Mike Agha.
Nell'intestazione
@interface YourViewController : UIViewController {
BOOL checkboxSelected;
UIButton *checkboxButton;
}
@property BOOL checkboxSelected;;
@property (nonatomic, retain) UIButton *checkboxButton;
-(void)toggleButton:(id)sender;
E nell'implementazione
// 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];
E mettere questo metodo in troppo:
- (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];
}
Everyones il codice qui è molto lungo, un po 'disordinato, e potrebbe essere fatto molto più semplice. Ho un progetto su GitHub che sottoclasse UIControl che è possibile scaricare e controllare e ti dà un elemento quasi nativa casella di controllo dell'interfaccia utente:
Sottoclasse UIButton, cadere un pulsante per visualizzare regolatore, selezionarlo e cambiare il nome classe per CheckBox nella finestra di ispezione identità.
#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
L'ho fatto con un UITextField per evitare di attirare qualcosa di strano, ma mi piaceva mettere dentro come testo Unicode tick (caratteri Unicode 'SPUNTA' (U + 2713)) per il NSString: @ "\ u2713".
In questo modo, nel mio file h (attuazione del protocollo per 'UITextFieldDelegate' l'UITextField):
UITextField * myCheckBox;
Nel mio viewDidLoad o la funzione di preparare l'interfaccia utente:
...
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!
...
Quindi, aggiungere un selettore evento per REAZIONE nel tocco manifestazione e chiamando evento 'responseSelected':
...
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(checkboxSelected)];
[myCheckBox addGestureRecognizer:tapGesture];
...
Infine rispondere a tale selettore
-(void) checkboxSelected
{
if ([self isChecked])
{
// Uncheck the selection
myCheckBox.text = @" -";
}else{
//Check the selection
myCheckBox.text = @"\u2713";
}
}
La funzione 'IsChecked' controlla solo se il testo è il "\ u2713" segno di spunta @. Per evitare che mostra la tastiera quando il campo di testo è selezionato utilizzare l'evento di 'textFieldShouldBeginEditing' l'UITextField e aggiungere il selettore di evento per gestire la selezione:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
// Question selected form the checkbox
[self checkboxSelected];
// Hide both keyboard and blinking cursor.
return NO;
}
nel file h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
BOOL isChecked;
UIImageView * checkBoxIV;
}
@end
E di file .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"];
}
}
Ciò farà il trucco ...
Mi piace l'idea di Adriano di utilizzare i personaggi piuttosto che le immagini. Ma non mi piace la casella, è necessario solo il segno di spunta in sé (@ "\ u2713"). Disegno un box (un box arrotondato) di programmazione ed effettuare un UILabel contiene il segno di spunta al suo interno. Questo modo di realizzazione lo rende facile da usare la visualizzazione personalizzata in qualsiasi applicazione, senza la cura di qualsiasi risorsa dipendente. È inoltre possibile personalizzare il colore del segno di spunta, la casella arrotondata e lo sfondo con facilità. Ecco il codice 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];
}
}
}
Ho fatto uno di recente. Liberi di acquisire da GitHub. Vedere se questo sarà di aiuto. L'effetto è simile
utente Aruna Lakmal; Cordiali saluti, quando si aggiunge questo codice a IB come lei initWithFrame non viene chiamato, è initWithCoder. Implementare initWithCoder e funzionerà come si descrive.














