xcode 以编程方式添加手势识别器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9352224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:21:38  来源:igfitidea点击:

adding gesturerecongnizer programmatically

iphoneobjective-ciosxcode

提问by

i know how to add a gesture recognizer via the IB but I'm trying to figure it out with out using IB.

我知道如何通过 IB 添加手势识别器,但我试图在不使用 IB 的情况下弄清楚。

So basically what have right now is

所以基本上现在有的是

blue1.userInteractionEnabled = YES;
UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] 
                               initWithTarget:self action:@selector(handlePan:)];

[blue1 addGestureRecognizer:pgr];
[pgr release];

and my handlePan is

我的 handlePan 是

-(IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

    CGPoint translation = [recognizer translationInView:self.view];

    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);

    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

}

this works fine if i do it over the IB and i am able to movie the piece around.

如果我在 IB 上做这件事并且我能够拍摄这件作品,这会很好用。

I dont understand what is causing it not to move like it is coded now.

我不明白是什么导致它不像现在编码那样移动。

Any help is appreciated.

任何帮助表示赞赏。

I also tried -(void) instead of -(IBAction) in my handlePan but that didn't work either.

我也在我的 handlePan 中尝试了 -(void) 而不是 -(IBAction) 但这也不起作用。

采纳答案by Rob Napier

The fact that this works in IB, but not in code suggests that the error is in the first block of code. My suspicion would be that blue1is nil. Make sure that you do not try to modify views before viewDidLoad. They will all be nilin initWithFrame:and awakeFromNib.

这在 IB 中有效,但在代码中无效,这一事实表明错误出在第一个代码块中。我的怀疑blue1nil。确保您之前不要尝试修改视图viewDidLoad。他们都将nilinitWithFrame:awakeFromNib