简体   繁体   中英

UITextField embedded in a UIView not responding to touch events

Why does a UITextField not respond to touch events when embedded in a UIView (which itself is embedded in the original view controller's main UIView )?

Here's the code:

- (void)loadView
{
    self.view = [UIView new];

    UIView *positionalView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];

    UITextField *usernameField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280, 50)];
    usernameField.placeholder = @"Full Name";
    usernameField.delegate = self;
    [usernameField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [positionalView addSubview:usernameField];

    UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 280, 50)];
    passwordField.placeholder = @"Password";
    passwordField.delegate = self;
    [passwordField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [positionalView addSubview:passwordField];

    [self.view addSubview:positionalView];
}

Finding it difficult to understand this behavior as the above code works fine, if I simply remove the positionalView and add the text fields directly to the main self.view.

Can anyone explain this?

You create a local variable named positionalView , but add the text fields to a property named positionalView . These are not the same variables.

You need bringSubviewToFront: :

[positionalView addSubview:usernameField];
[positionalView bringSubviewToFront:usernameField];

Same for passwordField and positionalView

The parent UIView's size is zero, pin the top, bottom, left and right constraints of the UITextField to the parent view so the parent view's size is the size of the UITextField, or set the frame of the parent UIView so that it has a size that is not zero.

Check the Debug View Hierarchy debug tool to check!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM