我有一个视图,其中有几条线在不同的方向上绘制。我需要确定用户点击了哪一行,然后做出相应的响应。
我脑子里有一些不同的想法,但我想要最好,最有效的方法来做到这一点......
最终,对我来说最有意义的是将每一行放在一个单独的视图中,并将其视为单个对象。如果我这样做,我需要将视图定位并旋转到该线的确切位置,以便我知道它何时被轻敲?如果不是,我会假设视图将相互重叠,我将无法确定哪个行被点击。
我希望我有意义。请告诉我实现这一目标的最佳方法。谢谢!
答案 0 :(得分:5)
对我来说,解决这个问题的最佳方法是创建UIView作为线条。如果它们只是纯色的线条,只需使用背景视图并相应地设置CGRectFrame。
为了对触摸事件做出反应而不处理位置等,在UIView的init方法中创建一个touchEvent,如下所示:
UITapGestureRecognizer *onTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lineClicked)];
[self addGestureRecognizer:onTap];
在UIView类中声明函数:
-(void)lineClicked {
//You can check some @property here to know what line was clicked for example
if (self.color == [UIColor blackColor])
//do something
else
//do another thing
// You can use a custom protocol to tell the ViewController that a click happened
(**) if ([self.delegate respondsToSelector:@selector(lineWasClicked:)]) {
[self.delegate lineWasClicked:self];
}
}
(**)您可能希望在单击该行后将一些逻辑放入viewController中。解决此问题的最佳方法是在CustomUIView.h文件中声明@protocol并将self作为参数传递,以便viewController知道被点击的人:
@protocol LineClikedDelegate <NSObject>
@optional
- (void)lineWasClicked:(UIView *)line; //fired when clicking in the line
@end
最后,在CustomUIView中创建一个@property以指向委托:
@property id<DisclosureDelegate> delegate;
在ViewController中。当您创建行时,UIViews将委托设置为:
blackLine.delegate = self.
在ViewController中实现方法- (void)lineWasClicked:(UIView *)line;
,然后进行设置。
答案 1 :(得分:1)