1

我正在尝试创建一个类似于按钮的 UIView 类。我想完全以编程方式完成。我能够让按钮出现,但它没有正确点击。

在我的类实现文件中,我有一个初始化方法以及以下内容:

- (void)handlePress:(UILongPressGestureRecognizer *)sender{
    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"in handlePress");
    }
}

在我的视图控制器实现文件中,我有:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.button = [[buttonclass alloc] initButton];
    [self.view addSubview: self.button];

    UILongPressGestureRecognizer *singlePress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePress:)];
    [self.button.buttonView addGestureRecognizer:singlePress];
}

(按钮是按钮类的实例变量,而按钮视图只是按钮的子视图)

我很确定问题出在以下几行之内:

UILongPressGestureRecognizer *singlePress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePress:)];
    [self.button.buttonView addGestureRecognizer:singlePress];

我什至不确定这些行是否应该放在按钮初始化函数或视图控制器实现文件中。我应该添加以下行吗?

singlePress.delegate = self;

我尝试添加该行,但我不知道将其放在哪里,并且错误说delegateandself不是同一类型。无论如何,当我尝试将 GestureRecognizer 连接到操作或将 GestureRecognizer 连接到 UIView 按钮时,出现了问题。

任何帮助将不胜感激!谢谢,祝你有美好的一天。

4

2 回答 2

0

您应该在按钮上而不是在按钮的子视图上添加手势。

UILongPressGestureRecognizer *singlePress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlePress:)];
[self.button addGestureRecognizer:singlePress];

无需添加以下行:

singlePress.delegate = self;
于 2013-07-05T18:39:12.830 回答
0

另外不要忘记释放 Button 对象,否则您可能会遇到内存泄漏,以防您忘记清理...

[super viewDidLoad];

self.button = [[buttonclass alloc] initButton];
[self.view addSubview: self.button];
[self.button release];

问候

于 2013-07-05T22:22:44.690 回答