Objective-C: addTarget:action:forControlEvent for subview button - iphone

I'm doing an iPhone ap which contains a viewController class (PhotoListViewController). This viewController's view has a subview which contains a button attached as a subview. I'm trying to use the addTarget:action:forControlEvent method to call an instance method of the PhotoListViewController class in order to perform an action when the button is pressed but the method is not being called. Any thoughts on how to make this work?
Here's the pertinent code. I know your first though will be why am I nesting subviews, but this just a distilled version of my program - there are reasons I'm doing the nesting. I know there are probably other ways of setting up the program so I don't have to do this nesting, but my real question is - why does this not work?
/Code/
#implementation PhotoListViewController
- (void)loadView {
[super viewDidLoad];
//load elements into the viewController
//first create the frame
CGRect frameParent = CGRectMake(0, 0, 0, 0);
UIView *viewPerson = [[UIView alloc] initWithFrame:frameParent];
CGRect frameChild = CGRectMake(0, 20, 0, 0);
UIView *newView = [[UIView alloc] initWithFrame:frameChild];
UIButton *btnShow = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnShow.frame = CGRectMake(230, 120, 80, 30);
[btnShow setTitle:#"View!" forState:UIControlStateNormal ];
[btnShow addTarget:self
action:#selector(viewPhoto_click:)
forControlEvents:UIControlEventTouchUpInside];
[newView addSubview:btnShow];
[viewPerson addSubview:newView];
[newView release];
[self setView:viewPerson];
[viewPerson release];
}
- (void)viewPhoto_click:(UIButton*)sender {
NSLog(#"HI");
}

It may not be related, but both viewPerson and newView have a width and height of 0. You may want to give these views a non-null size (the 3rd and 4th arguments of CGRectMake).

action:#selector(viewPhoto_click:)
forControlEvents:UIControlEventTouchUpInside];
May be a copy paste typo but have you tried to remove the : after the viewPhoto_click after the selector?
Also. In most examples the event Handler look like this.
- (void) viewPhoto_click: (id)sender
Not sure if it makes any difference though

Related

Very odd UIView position issue

I'm having a strange issue when it comes to adding content to a UIScrollView.
Below are the results for the same method getting called. The one on the left is the result of the call from viewDidLoad. The one one the right is called from a custom method which fires when the label is touched.
The code is pretty straight forward:
CGRect scrollRect = CGRectMake(0, 64, 320, [[UIScreen mainScreen] bounds].size.height - 49);
_containerView = [[UIScrollView alloc] initWithFrame:scrollRect];
_containerView.backgroundColor = [UIColor clearColor];
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 40)];
myLabel.text = #"my label";
myLabel.textColor = [super colorFromHexString:0x472C37];
myLabel.numberOfLines = 0;
[myLabel sizeToFit];
y_offset += myLabel.frame.size.height;
[_containerView addSubview:myLabel];
[self.view addSubView:_containerView];
I've checked the parent (self.view) and its coordinates are always 0,0. Really stumped by this...
In viewDidLoad your subViews components are not totally initialized yet, so if you are using the frame of some of them you will get an undesired result. viewDidLayoutSubviews is probably what you are looking for. This is the method where all the subviews frames are completly initialized.
Try to call your code inside this method and you should get the same result as the one when clicking in the button.
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self setupView];
}

Programmatically created button not firing event in custom view in iOS

On iOS, I created a button programmatically but the event is not firing.
UIButton * anyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[anyButton addTarget:self action:#selector(handleAnyButton:) forControlEvents:UIControlEventTouchUpInside];
anyButton.frame = CGRectMake(150, 350, 22, 22);
[self addSubview:anyButton];
The code is placed inside a custom view (not custom view controller), but I cannot make it fire the event. The press animation is not showing. The custom view has userInteractionEnabled enabled. I also tried using storyboard to create another button on the same view and that one is working. The button code is done in initWithFrame. Must be some simple error I haven't caught and I have been pounding my head over this one for hours.
EDIT:
The event handler:
-(void) handleAnyButton:(UIButton *)button
{
NSLog(#"handleAnybutton called");
}
EDIT2:
The above button codes is done within a [self setup] of class PKLocationsSelectionView.
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setup];
}
return self;
}
And this view was created programmatically within the view controller (PKLocSelectionViewController) responsible for this hierarchy:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
CGFloat fieldsHeight = 88;
UIView * view = [[PKLocationsSelectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, fieldsHeight)];
[self.view addSubview:view];
}
It looks like your button frame
anyButton.frame = CGRectMake(150, 350, 22, 22);
is outside of parent bounds
CGFloat fieldsHeight = 88;
UIView * view = [[PKLocationsSelectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, fieldsHeight)];
Here is the code that works for me:
MyCustomView.m:
#import "MyCustomView.h"
#implementation MyCustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 100, 100);
[button addTarget:self action:#selector(greet:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Greet" forState:UIControlStateNormal];
[self addSubview:button];
self.backgroundColor = [UIColor greenColor];
}
return self;
}
-(void) greet:(id) sender
{
NSLog(#"greet!");
}
And here is the ViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
MyCustomView *view = [[MyCustomView alloc] init];
view.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:view];
}
EDIT2: Could it be the Button is not fully enclosed within the coordinates of the container (PKLocationsSelectionView) view?
The height of the PKLocationsSelectionView is 88 from your code and the position of the button seems to be outside this. I think if the button is not enclosed within the frame of the superview then it won't receive touches.
Try and change your View initialization code in viewDidLoad, to give a static frame and see if it works..
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
CGFloat fieldsHeight = 88;
//See the change in below line.. instead of using self.view.bounds.size.width
// I used a static width.. 320 pixel for the moment..
UIView * view = [[PKLocationsSelectionView alloc] initWithFrame:CGRectMake(0, 0, 320.0, fieldsHeight)];
[self.view addSubview:view];
}
In viewDidLoad view hierarchy of controller will not be drawn completely..So self.view.bounds.size.width may be giving incorrect values.. To access self.view.frame and self.view.bounds, you should atleast wait until viewWillAppear gets called.
Also, your button origin.y is at 350 which in a view which has maximum height of only 88.. Any control outside parent's frame won't receive touches..

Improve Touch Events UIImageView

I have 30-40 tabs open, I've found my answer.. but I'm wishing to improve.
The code does work, I am just not sure if it is efficient
The following code shows that I have 2 small images (One using UIImageView, another using UIView) in which I have attached to a UIScrollView, which is attached to a UIView which came with the UIViewController, which is attached to the UIWindow. Pretty basic.
I also have a button attached to the UIViewController to make sure zooming and scrolling worked. (By testing the static location of the button and size)
#interface Wire_TestViewController : UIViewController <UIScrollViewDelegate> {
UIScrollView *scrollview;
}
#end
Implementation:
- (void)test:(UIButton *)sender { }
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return scrollview; }
- (void)viewDidLoad {
[super viewDidLoad];
scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
scrollview.delegate = self;
scrollview.contentSize = CGSizeMake( 320*2, 480*2 );
scrollview.minimumZoomScale = .1;
scrollview.maximumZoomScale = 10;
[self.view addSubview:scrollview];
UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(320, 320, 20, 20)];
view.image = [UIImage imageNamed:#"Node.png"];
view.clearsContextBeforeDrawing = NO;
[scrollview addSubview:view];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(10, 10, 100, 30);
button.tag = 51;
[button setTitle:#"new button" forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:#selector(test:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 30, 30)];
view2.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"WireActive.png"]];
[scrollview addSubview:view2];
TestSubclass *test = [[TestSubclass alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
test.userInteractionEnabled = TRUE;
test.image = [UIImage imageNamed:#"Node.png"];
[scrollview addSubview:test];
}
You'll see near the bottom I have a TestSubclass class made.
The code for that is as follows:
#interface TestSubclass : UIImageView { }
#end
#implementation TestSubclass
- (id)init {
[super init];
self.userInteractionEnabled = TRUE;
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
printf("Being touched...\n");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
printf("Touches Ended...\n");
}
#end
The part in which I am happy with is that I have a fully functioning Subclass of UIImageView which works as if it was a UIButton.
BUT! without the 7 backgroundImageViews (and the overhead from each of those), without the 6 labels (and the overhead from each of those), without the 6 UIImageViews ("..."), and lastly the amount of un-needed things that UIButton offers. I only wanted touch capabilities.. efficiently however. (TouchUpInside, Dragging, etc)
But, now during my research (after the extensive testing to accomplish this much), I've come across in documentation and some examples addGestureRecognizer in UIView. It seems sorta-but not entirely efficient for my needs.
I'm looking for advice, I know there are a couple problems in my code (overrided init, but didn't use it in the above code.. didn't release.. probably some subclassing mistakes (new to subClassing (to be honest)). But anything is much appreciated!! And, I hope others are helped as well!
If you want to have full control capabilities, you must subclass UIControl and use your image with in. The image can be an UIImageView subview or can be drawn in the drawRect method of your subclass or set in the CALayer view content.
Note that subclassing UIControl is not the easiest thing to do, but it gives you all "control" feature it seems you are requesting from it and I think is the most efficient or appropriate approach.

Best Practice to Float a View over Another View?

I have a 320x460 view with a number of buttons, depending on the button pressed, a 280x280 view pops up over the 320x460 view (similar to the behavior of the UIAlertView) using code like this:
UIView *overlayView = [[UIView alloc] initWithFrame:CGRectMake(20, 200, 280, 280)];
overlayView.backgroundColor = [UIColor whiteColor];
[overlayView autorelease];
[overlayView addSubview:label]; // label declared elsewhere
[overlayView addSubview:backgroundImage]; // backgroundImage declared elsewhere
//... Add a bunch of other controls
[label release];
[backgroundImage release];
//... Release a bunch of other controls
[self.view addSubview:overlayView];
Everything works fine displaying the overlayView and all its controls.
The question I have is, how do I get rid of the overlayView once it's displayed? I want to make it not only not visible but to remove it completely, since the user will be popping up the overlayView repeatedly during use.
You need access to overlayView to remove it, I'd suggest adding this to the create side:
overlayView.tag = 5; // Or some other non-zero number
Then later you can use it like this:
-(void)removeOverlayView
{
UIView *overlayView = [self.view viewWithTag:5];
[overlayView removeFromSuperview];
}

iPhone custom navigation bar with button doesnt click

Ive got an iPhone/iPad universal application and I wanted to have a custom navigation bar where the top half of the nav bar contained our companies logos, and the bottom half was the standard navigation bar.
I figured out how to do this, showing in the code below, but my UIButton "logosButton" doesnt always respond to being clicked, it appears as though only certain parts of the button are active, and others dont do anything at all... I cannot figure out why this is.
- (void)viewDidLoad {
[super viewDidLoad];
[[self view] addSubview: navController.view];
float width = IS_IPAD ? 768.0f : 320.0f;
float logosHeight = IS_IPAD ? 20.0f : 20.0f;
float barHeight = IS_IPAD ? 32.0f : 32.0f;
self.navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, logosHeight, width, barHeight)];
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, logosHeight)];
UIButton *logosButton = [[UIButton alloc] init];
[logosButton setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState:UIControlStateNormal];
[logosButton setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState:UIControlStateHighlighted];
[logosButton addTarget:self action:#selector(logosButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[logosButton setFrame: CGRectMake(0, 0, width, logosHeight)];
[tempView addSubview: logosButton];
[[self view] addSubview: tempView];
[tempView release];
[[self view] addSubview: self.navBar];
self.navItem = [[UINavigationItem alloc] initWithTitle: #"Home"];
[self.navBar pushNavigationItem:self.navItem animated:NO];
}
The method: logosButtonClicked does get fired every now and then when I click on the UIButton, but I clearly am clicking on certain spots where nothing happens at all...
Very frustrating, I dont seem, to see a pattern in regards to where its active, but could someone please help out here?
EDIT
I think I have just stumbled across something, I changed the button to a UIButtonTypeRoundedRect and got rid of the images (and also made it larger) and it appears that I cannot click on the bottom OR top sections of the button where the button is rounded. So the middle rectangular section is the only section where I can click... why would this be?
EDIT 2
For anyone reviewing this question, please see taber's latest edit on his answer. The Navigation Controller is eating touches for some reason, and I need to figure out why this is so, could be a bug?
FINAL ANSWER :)
Okay after reviewing the project it looks like the UINavigationController that is positioned below the button is eating touches globally. Which is definitely weird because it was added as a subview BELOW your button. So there must be some kind of funky frame/touch-eating going on with the UINavigationController. I tried to set navigationController.titleView.userInteractionEnabled = NO but to no avail. If anyone knows how to basically make UINavigationController and UINavigationBar not eat touches (I'm talking about the background where no buttons exist) then please chime in. The UIButton touches work just fine when the UINavigationController isn't added to the view.
Original Answer
It may be some other UI elements in [self view] or tempView sitting on top of the button and intercepting taps. You might want to try either commenting out everything else in the view(s) and/or try setting the userInteractionEnabled property on them like this:
[otherUIElement setUserInteractionEnabled: NO];
EDIT:
This code makes it so that you CAN click the round rect edges but NOT the title text. So I suspect that it's some sort of subview preventing the button from catching the tap.
[logosButton addTarget:self action:#selector(logosButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[logosButton setFrame: CGRectMake(0, 0, 320.0, 50.0)];
[logosButton setTitle: #"HELLO" forState: UIControlStateNormal];
[logosButton.titleLabel setUserInteractionEnabled: YES];
EDIT #2:
Try using this subclassed button and see if the issue still occurs:
// NavBtn.h
#interface NavBtn : UIButton {
}
-(id)initWithTitle:(NSString *)text;
#end
// NavBtn.m
#import "NavBtn.h"
#implementation NavBtn
- (id)initWithTitle:(NSString *)text {
if ((self = [super initWithFrame: CGRectMake(0, 0, 320, 50)])) {
[self setTitle: text forState: UIControlStateNormal];
self.backgroundColor = [UIColor clearColor];
self.opaque = NO;
[self setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState: UIControlStateNormal];
[self setBackgroundImage:[UIImage imageNamed:#"logo_bar_alone.png"] forState: UIControlStateHighlighted];
}
return self;
}
// i guess you shouldn't need to mess with layoutSubviews
#end
To load it into your view:
#import "NavBtn.h"
... in viewDidLoad, etc ...
NavBtn *btn = [[NavBtn alloc] initWithTitle: #"hey"];
[self.view addSubview: btn];
[btn release];
If THAT doesn't work, there's got to be some kind of third party library doing some funky category overriding of your UIButton class or something.