samedi 29 novembre 2014

UIView addSubview: only works for one of the two top level UIViews

I created a simple app to test the UIResponder touchesBegan method. I tried to add a text field with origin at the point where the click was on the view.


But I ran into this strange situation of [UIView addSubview:] only working for one of the two subviews under the top view, using the same code segment of touchesBegan.


The single view app was created with interface builder, with very simple views:



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


The settings from IB for both view 1 and view 2 are the same. The two views just stack up, one on top of the other, with two rectangles splitting a portrait iphone view into two equal parts.


When I executed the code segment, the newly added text field only showed up for the rectangle on the top part of the portrait view, not the second one, regardless of whether it is view 1 or view 2 (I swapped the positions of the two sub views just to test). NSLog showed that the code segment executed exactly the same for both views.



- (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];

}


Any idea what is going on and how to fix it?




Aucun commentaire:

Enregistrer un commentaire