泛手势不适用于Uiswitch

时间:2012-08-15 10:02:37

标签: iphone ios5 uiswitch uipangesturerecognizer

我添加了一个uiswitch并希望通过手势将其移动到另一个位置。但是uipangesture没有在uiswitch上工作..下面是我的代码

    UISwitch *swich = [[UISwitch alloc]initWithFrame:CGRectMake(20, 20, 40, 50)];

    swich.userInteractionEnabled = YES;

    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] 
                                       initWithTarget:self 
                                       action:@selector(switchdraged:)];
    [swich addGestureRecognizer:gesture];

    [self.view addSubview:swich];

函数switchdraged未被调用..

下面是switchdraged函数

- (void)switchdraged:(UIPanGestureRecognizer *) gesture1
{
        UISwitch *swich = (UISwitch *)gesture1.view;
        CGPoint translation = [gesture1 translationInView:swich];
        swich.center = CGPointMake(swich.center.x + translation.x, 
                                swich.center.y + translation.y);
        // reset translation
        [gesture1 setTranslation:CGPointZero inView:swich];
}

1 个答案:

答案 0 :(得分:1)

我认为UIPanGestureRecognizer不适用于UISwitch

班级参考说

  

UIPanGestureRecognizer是UIGestureRecognizer的具体子类   寻找平移(拖动)手势。用户必须按   视图上的一个或多个手指在它们平移时。

SO UISwitch可能因改变状态而被覆盖

我创建了一个示例应用程序

相同的代码与UILabel代替UISwitch效果很好。我和Abizern讨论过了。他告诉我,可能因改变状态而被覆盖

请详细说明您需要使用UISwitch做什么。

这种方式可以帮助你

1.在视图中创建一个开关并添加为子视图

- (void)viewDidLoad
{  

    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];  
    containerView.backgroundColor = [UIColor blackColor];
    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] 
                                       initWithTarget:self 
                                       action:@selector(switchdraged:)];
    [containerView addGestureRecognizer:gesture];


    UISwitch *swich = [[UISwitch alloc]initWithFrame:CGRectMake(20, 20, 40, 50)];    
    swich.userInteractionEnabled = YES;



    [containerView addSubview:swich];    

    [self.view addSubview:containerView];
    [self.view bringSubviewToFront:containerView];


    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)switchdraged:(UIPanGestureRecognizer *) gesture1
{
    NSLog(@"triggered");

    UIView *swich = (UIView *)gesture1.view;
    CGPoint translation = [gesture1 translationInView:swich];
    swich.center = CGPointMake(swich.center.x + translation.x, 
                               swich.center.y + translation.y);
    // reset translation
    [gesture1 setTranslation:CGPointZero inView:swich];
}

此链接可以帮助您

Draggable Buttons and Labels

相关问题