ios当我从xib点击时如何知道哪个UIView?

时间:2015-05-05 07:42:59

标签: ios objective-c xcode uiview xib

由于某些原因,我创建了一个UIView xib文件来重用 当我从xib点击时如何知道哪个UIView?

我创建了一个扩展UIView的xib文件(用XibView命名) 然后我在故事板中拖动两个UIView(leftView,rightView),并设置自定义类" XibView"在XCode检查器窗口中。

当我编译代码时,它将得到显示两个UIViews的正确结果。

下面的XibView.m文件部分代码:

 -(id) initWithCoder:(NSCoder *)aDecoder
 {
     self = [super initWithCoder:aDecoder];

     if( self )
     {

          UIView *containerView = [[[UINib nibWithNibName:@"XibView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
          CGRect newFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
          containerView.frame = newFrame;
          [self addSubview:containerView];
     }
    return self;
 }

 -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
      NSLog(@"tap in xib");
      ......
 }

但我怎么知道哪个UIView是我的点击?

//我添加了一些详细说明。

在xib自定义类中,我将使用post发布到uiviewcontroller并在用户单击xib时获取一些数据(touchesBegan在xib自定义类中)。

我在故事板中有两个uiview,这些uiview将使用xib文件。

所以我想知道当我点击哪个uiview时,我可以知道哪个用户点击了。

// -------------回答。请参考@Boyi Li的回答。 ---------

在XibView.m中添加了

[super touchesBegan:touches withEvent:event];

覆盖触摸开始方法。

并在viewcontroller中添加XibView头文件。

它可以将引用拖动到viewcontroller。

2 个答案:

答案 0 :(得分:0)

如您所说,您可以为这两个视图指定不同的标记。在XibView内,您可以查看self.tag == <tag>

如果要在父视图或控制器中获取特定视图,请使用viewWithTag:方法。它将检查其tag属性是否与tag参数中的值匹配的层次结构。

<强>更新

在ViewController中为左视图和右视图创建IBOutlet参考。在您的控制器中,您有:

@property (nonatomic, weak) IBOutlet XibView *leftView;
@property (nonatomic, weak) IBOutlet XibView *rightView;`

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
     UITouch *touch = [[event allTouches] anyObject];
     CGPoint leftTouchPoint = [touch locationInView:leftView];
     CGPoint rightTouchPoint = [touch locationInView:rightView];
     if ([self.leftView pointInside:leftTouchPoint withEvent:event]) {
         // Do something for leftView
     } else if ([self.rightView pointInside:rightTouchPoint withEvent:event]) {
         // Do something for Right View
     }
 }

答案 1 :(得分:0)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
  {

    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    if ([touch.view isKindOfClass: UIView.class])
    {
      UIView *view=touch.view;
      if (view==YourView1)
      {
        //start editing

      }else
      if (view==YourView2)
      {
        //start editing

      }
   }
   else
   {

   }
 }