views:

131

answers:

2

I'm programmatically creating a UIButton for my app. The few examples I've found online seem straightforward. Following the examples, I can create a button fine but it fails to do the action for TouchDown event I have wired for it. Here is the code for the button inside the ViewDidLoad of the parent view:

        _searchButton = UIButton.FromType(UIButtonType.RoundedRect);
        _searchButton.Frame = new RectangleF(swidth / 2 - 50f, 140f, 100f, 40f);
        //_searchButton.BackgroundColor = UIColor.Clear;
        _searchButton.SetTitle("Search", UIControlState.Normal);
        _searchButton.SetTitleColor(UIColor.Black, UIControlState.Normal);
        _searchButton.UserInteractionEnabled = true;
        _searchButton.TouchDown += delegate
        {
            Console.WriteLine("wicked");
        };
        this.View.AddSubview(_searchButton);

The only thing I can think of possibly the setting of UserInteractionEnabled. But they seem to be set to true by default. (Explicitly setting it true for the button doesn't help.)

What could I be doing wrong here?

I should add that the button should turn blue when I click on it, even if nothing is wired for TouchDown? That doesn't happen either.

A: 

More context then the answer. The search button has a textfield sibling, both held by a container UIViewController. That parent container is a sibling of a TableViewController. Both the uivc and the tvc are held by an outer container.

My code was

View.AddSubview(uivc);
View.AddSubview(tvc);

in the outermost container.

Table works fine, uivc controls do not. If I reverse the order, both work fine!

View.AddSubview(tvc);
View.AddSubview(uivc);

Go figure.

HappyCoder
A: 

The way to handle a TouchDown event is to use a target-action method. Here is an example:

// button action method declaration
UIButton *buttonTemp = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonTemp addTarget:self action:@selector(favoriteTapped:event:) 

//method to fire when the button is touched

- (void)favoriteTapped:(id)sender event:(id)event
{
    NSLog(@"favoriteTapped");
}

In a nutshell, the second line in the button declaration says: "When the button is touched, fire the 'favoriteTapped method'

dpigera