1

我添加了一个 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没有被调用..

下面是开关拖动功能

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

1 回答 1

1

我认为UIPanGestureRecognizer不会与UISwitch.

类参考说

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

所以 UISwitch 可能被覆盖以更改状态

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

相同的代码与UILabel而不是UISwitch. 我已经和阿比森讨论过了。他告诉我,它可能会因为改变状态而被覆盖

请描述好你需要用 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];
}

或者

此链接可能对您有所帮助

可拖动的按钮和标签

于 2012-08-15T11:43:44.783 回答