UIView addSubview:仅适用于两个顶级UIView之一

时间:2014-11-29 19:37:28

标签: ios objective-c iphone uiview

我创建了一个简单的应用来测试UIResponder touchesBegan方法。我尝试在点击视图的位置添加带原点的文本字段。

但是我遇到了[UIView addSubview:]这种奇怪的情况,只使用了topches视图下的两个子视图之一,使用了touchesBegan的相同代码段。

单一视图应用程序是使用界面构建器创建的,具有非常简单的视图:

- view controller
  |
  --view 
      |
      -- view (tag 1)
      |
      -- view (tag 2)

视图1和视图2的IB设置是相同的。两个视图叠加在一起,一个在另一个上面,两个矩形将纵向iphone视图分成两个相等的部分。

当我执行代码段时,新添加的文本字段仅显示纵向视图顶部的矩形,而不是第二个,无论是视图1还是视图2(我交换了位置)两个子视图只是为了测试)。 NSLog显示两个视图的代码段执行完全相同。

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

    UITouch* tch = [touches anyObject];
    UIView* currentView = tch.view;

    self.pt = [tch locationInView:self.view];

    CGRect rect = CGRectMake(self.pt.x, self.pt.y, 300,30);

    UITextField *tf = [[UITextField alloc] initWithFrame:rect];

    NSMutableString* str = [[NSMutableString alloc]init];

    [str appendString:@"clicked view "];

    [str appendString:tg];

    tf.text = str;
    tf.backgroundColor =[UIColor whiteColor];

    [currentView addSubview:tf];

    //added after failed to add text field to the second view

    [currentView bringSubviewToFront:tf];

}

知道发生了什么以及如何解决它?

1 个答案:

答案 0 :(得分:0)

文本字段的框架应该位于您要添加到的视图的坐标系中,而不是self.view的坐标系 - 它适用于顶视图,因为它和自身。视图具有相同的起源。你需要改变self.pt的定义,

self.pt = [tch locationInView:currentView];
相关问题