确定在视图中绘制的线是否被点击的最佳方法是什么?

dig*_*lls 1 objective-c ios

我有一个视图,其中有几条线在不同的方向绘制.我需要确定用户点击了哪条线然后做出相应的响应.

我脑子里有几个不同的想法,但我想要最好,最有效的方法来做到这一点......

最终,对我来说最有意义的是将每一行放在一个单独的视图中,并将其视为单个对象.如果我这样做,我需要将视图定位并旋转到该线的确切位置,以便我知道它何时被轻敲?如果不是,我会认为视图将相互重叠,我将无法确定哪个线被点击.

我希望我有意义.请告诉我实现这一目标的最佳方法.谢谢!

Pau*_*uls 5

对我而言,解决这个问题的最佳方法是创建UIView作为线条.如果它们只是纯色的线条,只需使用背景视图并相应地设置CGRectFrame.

为了对触摸事件做出反应而不处理位置等,在UIView的init方法中创建一个touchEvent,如下所示:

UITapGestureRecognizer *onTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lineClicked)];
 [self addGestureRecognizer:onTap];   
Run Code Online (Sandbox Code Playgroud)

在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];
     }
}
Run Code Online (Sandbox Code Playgroud)

(**)您可能希望在单击该行后将一些逻辑放入viewController中.解决此问题的最佳方法是在CustomUIView.h文件中声明@protocol并将self作为参数传递,以便viewController知道被点击的对象:

@protocol LineClikedDelegate <NSObject>
@optional
- (void)lineWasClicked:(UIView *)line; //fired when clicking in the line
@end
Run Code Online (Sandbox Code Playgroud)

最后,在CustomUIView中创建一个@property来指向委托:

@property id<DisclosureDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)

并在ViewController中.当您创建行时,UIViews将委托设置为:

blackLine.delegate = self.
Run Code Online (Sandbox Code Playgroud)

- (void)lineWasClicked:(UIView *)line;在ViewController中实现该方法并进行设置.