对我来说,解决这个问题的最佳方法是将 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; 方法就可以了。