为什么我点击UISwitch,它不起作用?

时间:2013-08-07 06:47:35

标签: ios uiswitch

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

    if (self) {
        self.sw = [[[UISwitch alloc] initWithFrame:CGRectMake(210, 8, 50, 30)] autorelease];
       [sw setOn:YES];
        [sw addTarget:self action:@selector(switchChanged) forControlEvents:UIControlEventTouchUpInside];

       [self addSubview:sw];
    }

    return self;
}

-(void)switchChanged
{
    //    [self setImage];
    [sw setOn:NO];
    if (_delegate && [_delegate respondsToSelector:@selector(selectedWith:)]){
        [_delegate selectedWith:self];
    }
}

当我点击开关,但是函数switchChanged没有被调用?

2 个答案:

答案 0 :(得分:1)

forControlEvents更改为 UIControlEventValueChanged ,而不是UIControlEventTouchUpInside

试试这个,

 [sw addTarget:self action:@selector(switchChanged) forControlEvents:UIControlEventValueChanged];

答案 1 :(得分:0)

因为当您需要更改UISwitch中的值时,您指定的事件应为 UIControlEventValueChanged

[sw addTarget:self action:@selector(switchChanged) forControlEvents: UIControlEventValueChanged];