简体   繁体   中英

UIButtons not working on programmatically created UIView

I have a UIViewController which I want to display a UIView that renders as a menu. This menu will have several buttons on it. I wanted to reuse this menu a few different places in my app so I figured I would create a class called ViewFactory that has a method that returns a UIView with these buttons.

On my ViewController I call this method and get the returned UIView and add it as a subview.

This works just fine. I can see the view and all its buttons, however, the buttons do not respond to any touch events. Not sure why this is the case and curious to know what I am doing wrong.

Here is my code for the ViewFactoryClass :

- (UIView *) addCloseRow
{
    // UIView container for everything else.
    UIView *navRow = [[UIView alloc] initWithFrame:CGRectMake(0,225,350,45)];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.userInteractionEnabled = YES;

    [navRow addSubview:button];

    [button addTarget:self action:@selector(closeButtonTouchDownEvent) forControlEvents: UIControlEventTouchDown];
    navRow.userInteractionEnabled = YES;
    return navRow;
}

In my main NavigationController class here is how I am calling and getting the UIView :

ViewFactory *factory = [[ViewFactory alloc] init];
[self.navigationController.navigationBar addSubview:[factory MainNavigationUIView]];

Again, the UIView shows up but the buttons never respond to anything.

You added the button with target and selector for ViewFactoryClass

And now you are creating instance and trying to call an action from ViewFactory class.

You can change the method to something like this:

- (UIView *) addCloseRow : (id)object {
    ...
    [button addTarget:[object class] action:@selector(closeButtonTouchDownEvent) forControlEvents: UIControlEventTouchDown];
    ...
}

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