【发布时间】:2014-01-24 13:53:12
【问题描述】:
我的程序中有一个主视图,其中有一个可拖动的视图。可以使用平移手势拖动此视图。目前虽然它使用了很多我想放在子类中以降低复杂性的代码。 (我最终希望通过允许用户通过进一步的平移手势来扩展视图来增加功能。这意味着如果我不能先解决这个问题,将会有更多的代码阻塞我的视图控制器)
是否可以在类的子类中拥有手势识别器的代码,并且仍然与父类中的视图交互。
这是我用于在父类中启用平移手势的当前代码:
-(void)viewDidLoad {
...
UIView * draggableView = [[UIView alloc]initWithFrame:CGRectMake(highlightedSectionXCoordinateStart, highlightedSectionYCoordinateStart, highlightedSectionWidth, highlightedSectionHeight)];
draggableView.backgroundColor = [UIColor colorWithRed:121.0/255.0 green:227.0/255.0 blue:16.0/255.0 alpha:0.5];
draggableView.userInteractionEnabled = YES;
[graphView addSubview:draggableView];
UIPanGestureRecognizer * panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panWasRecognized:)];
[draggableView addGestureRecognizer:panner];
}
- (void)panWasRecognized:(UIPanGestureRecognizer *)panner {
UIView * draggedView = panner.view;
CGPoint offset = [panner translationInView:draggedView.superview];
CGPoint center = draggedView.center;
// We want to make it so the square won't go past the axis on the left
// If the centre plus the offset
CGFloat xValue = center.x + offset.x;
draggedView.center = CGPointMake(xValue, center.y);
// Reset translation to zero so on the next `panWasRecognized:` message, the
// translation will just be the additional movement of the touch since now.
[panner setTranslation:CGPointZero inView:draggedView.superview];
}
(Thanks to Rob Mayoff for getting me this far)
我现在已经添加了视图的子类,但无法弄清楚我需要如何或在何处创建手势识别器,因为现在正在子类中创建视图并添加到父类中。
我真的希望手势识别器的目标在这个子类中,但是当我尝试对其进行编码时,没有任何反应。
我尝试将所有代码放入子类中并将平移手势添加到视图中,但是当我尝试拖动它时,我遇到了错误的访问崩溃。
我目前正在尝试使用
[graphView addSubview:[[BDraggableView alloc] getDraggableView]];
将其添加到子视图中,然后在子类的函数 getDraggableView 中设置视图(添加平移手势等)
必须有一种更直接的方式来做这件事,但我还没有概念化——我在处理子类方面还是个新手,所以我还在学习它们是如何组合在一起的。
感谢您提供的任何帮助
【问题讨论】:
标签: ios objective-c inheritance subclass uipangesturerecognizer