iOS uygulamasında Onay Kutusu

oy
34

Benim forma onay kutusu denetimleri eklemek gerekir. IOS SDK içinde böyle bir denetim yok olduğunu biliyoruz. Bunu nasıl yapabilirdi?

Oluştur 16/03/2009 saat 13:05
kaynak kullanıcı
Diğer dillerde...                            


13 cevaplar

oy
31

Bu da beni deli olmuştur ve benim için iyi çalışıyor ve görüntüleri kullanmak zorunda önler farklı bir çözüm buldu.

  1. Interface Builder için yeni bir etiket nesnesi ekleyin.
  2. Xcode bir IBOutlet mülk oluşturun ve ona o kadar bağlayın. Birisi tamamen bir miktar para ödedi olmadığını bilmek istiyorum ben aradım Aşağıdaki kodda 'fullyPaid'.
  3. Aşağıdaki 2 işlevler ekleyin. 'TouchesBegan' işlevini kontrol eder 'fullyPaid' etiketi nesnesinin içinde bir yere dokunursa ve eğer öyleyse, bu togglePaidStatus 'işlevini çağırır. 'TogglePaidStatus' işlevi boş bir kutu (\ u2610) ve (\ u2611) sırasıyla bir kutuyu işaretli temsil unicode karakter iki dizeyi kurar. Sonra 'fullyPaid' nesne şu anda var ve diğer dize ile değiştirir neyi karşılaştırır.

Başlangıçta boş bir dizeye ayarlamak için viewDidLoad işlevinde togglePaidStatus işlevi çağırmak isteyebilirsiniz.

Açıkçası etiket etkin değilse onay kutusunu geçiş kullanıcıların önlemek için ekstra kontroller ekleyebilir, ama bu aşağıda gösterilen değil.

-(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];
}
Cevap 10/04/2010 saat 22:23
kaynak kullanıcı

oy
26

Genellikle, onay kutusu benzeri işlevsellik için UISwitch kullanmak.

Onların kontrolünü dokunduğunuzda iki resim (kontrol / denetlenmeyen) ile bir görüntü kontrolü kullanarak ve görüntüleri geçiş yaparak olsa kendi rulo olabilir /

Cevap 16/03/2009 saat 13:12
kaynak kullanıcı

oy
10

Seçeneklerin bir grup gösteriyoruz ve kullanıcı bunlardan birini seçebilir Eğer bir onay işareti aksesuar ve seçilen satırda farklı bir metin rengi ile bir tableView kullanın.

Tek bir seçeneğiniz varsa, en iyi bahis bir anahtar kullanmaktır. Eğer onay kutusu boş bir kutu ve seçilen görüntüye normal bir görüntü ayarı, bir düğme kullanmak istemeyen veya Eğer. Sen bu iki görüntüleri kendiniz yapmak ya da onlar için kullanmak stok grafikleri bulmak gerekecek.

Cevap 16/03/2009 saat 13:33
kaynak kullanıcı

oy
8

Için genişletme adrean fikri , ben çok basit bir yaklaşım kullanarak bunu başardık.
Benim fikrim (diyelim düğmesine değiştirmektir checkBtn) Metin onun durumuna bağlı ve sonra onun içinde düğmenin durumunu değiştirme IBAction.
Aşağıda ben bu nasıl yaptığını kod şudur:

- (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
    }
}
Cevap 19/03/2014 saat 05:17
kaynak kullanıcı

oy
6

İşte iphone için onay kutusunu benim sürümüdür.

Bu UIButton uzanan bir sınıftır. ben buraya yapıştırın olacak böylece basit.

CheckBoxButton.h dosya içeriği

#import <UIKit/UIKit.h>

@interface CheckBoxButton : UIButton

@property(nonatomic,assign)IBInspectable BOOL isChecked;

@end

CheckBoxButton.m dosya içeriği

#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

Sen görsel stüdyo nitelik denetiminde kontrol / denetlenmeyen yanı sıra isChecked özellik için görüntüleri ayarlayabilirsiniz.

Burada görüntü açıklama girin

Bir sonraki görüntüye gibi film şeridinde veya xib, basit eklenti UIButton ve set özel sınıfında CheckBoxButton ekleyin.

Burada görüntü açıklama girin

Düğme UIControlEventValueChanged olayı, isChecked devlet her değiştiğinde gönderir.

Cevap 31/12/2014 saat 13:44
kaynak kullanıcı

oy
6

Ben programlı Bunu yapmak, hem de isabet alan gerçekten çok küçüktü sorunu çözmek istedik. Bu Mike ve Ahmet'in yorumcu Ağa dahil olmak üzere çeşitli kaynaklardan uyarlanmıştır.

Başlığınızda

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

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

-(void)toggleButton:(id)sender;

Ve uygulanmasında

// 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];

Ve çok bu yöntemi koymak:

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

}
Cevap 21/05/2010 saat 17:46
kaynak kullanıcı

oy
4

Burada herkesin kod biraz dağınık, çok uzun ve çok daha kolay yapılabilir. Ben indirip kontrol etmek ve size neredeyse yerli onay kutusu UI öğesi verir ki UIControl alt sınıf GitHub'dan bir projesi var:

https://github.com/Brayden/UICheckbox

Cevap 18/07/2012 saat 08:03
kaynak kullanıcı

oy
1

Alt sınıf UIButton, kontrolör görüntülemek seçin ve kimlik denetiminde CheckBox sınıf adını değiştirmek için bir düğme bırakın.

#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
Cevap 13/05/2015 saat 11:59
kaynak kullanıcı

oy
1

Garip bir şey çizim önlemek için bir UITextField ile yapılan ama NSString için kene Unicode metin olarak içeride ( 'MARK GÖR' Unicode Karakter (U + 2713)) koyarak sevdim: "\ u2713" @.

Benim .h dosyasında (UITextField 'UITextFieldDelegate' protokolünü uygulayan) Bu şekilde:

UITextField * myCheckBox;

Benim viewDidLoad veya işlevde UI hazırlamak için:

...
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!
...

Ardından, dokunmatik olay reating ve 'responseSelected' olayını çağırmak için bir olay seçici eklemek:

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

Nihayet o seçicinin cevap

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

Metin @ "\ u2713" onay işareti ise işlevin yalnızca çek 'isChecked'. Metin alanı seçimini yönetmek için UITextField 'textFieldShouldBeginEditing' olay kullanmak ve olay seçici eklemek seçildiği klavyeyi gösteren önlemek için:

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

    // Hide both keyboard and blinking cursor.
    return NO;
}
Cevap 07/10/2014 saat 12:13
kaynak kullanıcı

oy
1

.h dosyasında

#import <UIKit/UIKit.h>

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

Ve .m dosyası

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

Bu hile olacaktır ...

Cevap 14/06/2013 saat 11:12
kaynak kullanıcı

oy
1

Adrian fikri görüntüleri ziyade karakterleri kullanmak ister. Ama bu sadece onay işareti kendisi ( "\ u2713" @) Gereksiz, kutuyu sevmiyorum. Ben programlı bir kutu (yuvarlak kutu) çizip bir UILabel içindeki onay işaretini içerir yerleştirin. uygulama Bu şekilde kolay bağımlı kaynak hakkında bakım olmadan herhangi bir uygulamada özel görünümü kullanmayı kolaylaştırır. Ayrıca onay işareti rengini, yuvarlak kutu ve kolaylıkla arka plan özelleştirebilirsiniz. İşte tam kodu:

#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];
        }
    }
}
Cevap 23/07/2010 saat 10:41
kaynak kullanıcı

oy
0

Geçenlerde birini yaptı. GitHub elde etmek ücretsiz. Bak bakalım bu yardımcı olacaktır. Etkisi gibidir

Burada görüntü açıklama girin

Cevap 01/04/2019 saat 20:36
kaynak kullanıcı

oy
0

Kullanıcı Aruna Lakmal; Eğer initWithFrame çağrılmaz açıklayan gibi IB için bu kodu eklerken Bilginize, initWithCoder olduğunu. initWithCoder uygulamak ve açıkladığınız gibi çalışacaktır.

Cevap 20/01/2013 saat 04:15
kaynak kullanıcı

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