How to add a UIButton at runtime - iphone

I am trying to add a UIButton at runtime however it is not visible. What am I doing wrong?
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
UIButton *btn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:#"Play" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(buttonClick:)
forControlEvents:UIControlEventTouchUpInside];
btn.center = self.center;
[self addSubview:btn];
}
return self;
}

First, make sure the initWithFrame: method is being called. If your view is in a Nib, initWithCoder: is being called instead.
Second, is the button the only subview (from your code it looks like it is, but you never know). The button could be hidden behind another subview. Call bringSubviewToFront: if you need to.
Finally, is the view itself visible? Is it big enough to show the button? Given your example, if the view is less than 100 pixels wide, the button won't show because it will get clipped by the view's bounds.

You must release btn and remove ":" in buttonClick:
UIButton *btn= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
btn.frame = CGRectMake(0, 0, 100, 25);
btn.backgroundColor = [UIColor clearColor];
[btn setTitle:#"Play" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[btn release];

if it still doesn't work, try removing the : at the end of the selector name: #selector(buttonClick)

You don't need to retain the UIButton because it is retained by [self.view addSubview:btn];

First check whether your code is executing the initwithFrame method.
Because if you are loading the view from nib i.e using
NSArray *xibviews = [[NSBundle mainBundle] loadNibNamed: #"MySubview" owner: mySubview options: NULL];
MySubview *msView = [xibviews objectAtIndex: 0];
[self.view addSubview:msView];
Then the initWithFrame part will not be executing.So please check once.

Related

UIButton not calling target's selector

I have a button that doesn't call its target's selector.
When I click it, it does get highlighted. However, I set a break point at playButtonClicked and it never gets reached.
I'm not sure if it's being released, but I don't think so. I have ARC enabled and I can't call retain or release.
I've also tried explicitly enabling userInteractionEnabled but that doesn't make a difference either.
Here is my code:
#import "MainMenuView.h"
#implementation MainMenuView
- (void)initializeButton:(UIButton*)button withText:(NSString*)text buttonHeight: (int)buttonHeight buttonWidth:(int)buttonWidth buttonYInitialPosition:(int)buttonYInitialPosition buttonXPosition:(int)buttonXPosition
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(buttonXPosition, buttonYInitialPosition, buttonWidth, buttonHeight);
button.backgroundColor = [UIColor clearColor];
[button setBackgroundImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
[button setTitle:text forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont boldSystemFontOfSize:24];
[self addSubview:button];
[self bringSubviewToFront:button];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor yellowColor];
UIImage *backgroundImage = [UIImage imageNamed:#"title_background.jpeg"];
UIImageView *background = [[UIImageView alloc] initWithFrame:frame];
background.image = backgroundImage;
background.backgroundColor = [UIColor greenColor];
[self addSubview:background];
int centerWidth = frame.size.width / 2;
int centerHeight = frame.size.height / 9;
int centerXPos = frame.size.width / 4;
int buttonYInitialPosition = frame.size.height / 2 + frame.size.height / 20;
int buttonYOffset = frame.size.height / 7;
// init buttons
[self initializeButton:playButton withText:#"Play" buttonHeight:centerHeight buttonWidth: centerWidth
buttonYInitialPosition:buttonYInitialPosition buttonXPosition:centerXPos];
[playButton addTarget:self action:#selector(playButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void) playButtonClicked:(id)sender
{
NSLog(#"Play Button Clicked");
}
#end
Your code isn't doing what you think it is.
When you pass playButton in to -initializeButton:... and then immediately create a new button and assign it to that variable, you're no longer operating on the value that playButton points to. So when you call -addTarget:action:forControlState: afterwards, you're assigning a target to whatever playButton happens to point to, which is not the button you just created and added.
Passing a pointer is done (by default) by value, which means that you only have the address that the pointer held, not a reference to the pointer itself. So you can't change the pointer itself, only the object it points to. You can pass the pointer by reference, if you want to modify what it points to; or you can restructure your code so that you're always acting on the pointer directly—for instance, you could just use an ivar or property and have your initialize method set that property. Or you could return the button and assign it to your variable or property.
You are initializing the button incorrectly. A better approach is to have your initializeButton return the button.
- (UIButton *)initializeButtonWithText:(NSString*)text buttonHeight: (int)buttonHeight buttonWidth:(int)buttonWidth buttonYInitialPosition:(int)buttonYInitialPosition buttonXPosition:(int)buttonXPosition
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(buttonXPosition, buttonYInitialPosition, buttonWidth, buttonHeight);
button.backgroundColor = [UIColor clearColor];
[button setBackgroundImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
[button setTitle:text forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
button.titleLabel.font = [UIFont boldSystemFontOfSize:24];
[self addSubview:button];
[self bringSubviewToFront:button];
return button;
}
Then call it this way:
playButton = [self initializeButtonWithText:#"Play" buttonHeight:centerHeight buttonWidth: centerWidth
buttonYInitialPosition:buttonYInitialPosition buttonXPosition:centerXPos];
I think you should do your initialization stuff in the method:
-(void)awakeFromNib {}
It's like the -viewDidLoad method for custom UIViews in that all the nib objects have been loaded and ready to go.
In the first line of your initializeButton method, you create a new Button. This new button is styled and added to the view hierarchy. This is the button that you see and that you can tap when you launch your app.
However, you apparently have another button named playButton. You pass it into the initializeButton method, but as written above, don't do anything with that reference. That means the addTarget: call goes to a button that you never add to your view hierarchy.

How to create multiline backBarButtonItem in UINavigationBar

I want to create multiline BackBarButtonItem. right now my back button display like this,
but i want to display it like this, color does not matter,
How can I do that? And this is my default back button which added while i am pushing my childviewcontroller thru my parentviewcontroller so i dont want to remove it.
You can do it using custom image,UILabel(MSLabel),UIButton.
MSLabel is used to change space between two line of UILabel. Because UILabel Does not provide any property to do that.
After you add MSLabel in your project use this code. Recommend size for backbtn.png is 48*30.
#import "MSLabel.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the custom back button
UIImage *buttonImage = [[UIImage imageNamed:#"backbtn.png"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 5)];
//create the button and assign the image
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
MSLabel *lbl = [[MSLabel alloc] initWithFrame:CGRectMake(12, 4, 65, 28)];
lbl.text = #"Account Summary";
lbl.backgroundColor = [UIColor clearColor];
//lbl.font = [UIFont fontWithName:#"Helvetica" size:12.0];
lbl.numberOfLines = 0;
lbl.lineHeight = 12;
lbl.verticalAlignment = MSLabelVerticalAlignmentMiddle;
lbl.font = [UIFont fontWithName:#"Helvetica" size:12];
[button addSubview:lbl];
//set the frame of the button to the size of the image (see note below)
button.frame = CGRectMake(0, 0, 70, buttonImage.size.height);
[button addTarget:self action:#selector(back) forControlEvents:UIControlEventTouchUpInside];
//create a UIBarButtonItem with the button as a custom view
UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = customBarItem;
}
-(void)back {
NSLog(#"Dilip Back To ParentViewController");
// Tell the controller to go back
[self.navigationController popViewControllerAnimated:YES];
}
Outcome will display like this, Use your image for better result.
In this case you should use custom button and use background image on this button.Because i think it may not be possible.See for custom button
UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10.0f,6.5f,60.0f,30.0f)];
[backBtn setBackgroundImage:[UIImage imageNamed:#"accountSummary"] forState:UIControlStateNormal];
[backBtn setBackgroundImage:[UIImage imageNamed:#"accountSummary"] forState:UIControlStateHighlighted];
[backBtn addTarget:self action:#selector(accountSummaryBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
[self.navigationItem setLeftBarButtonItem:leftButton];
- (void)accountSummaryBtnPressed:(id)sender
{
//--------- do stuff for account summary
}
What i believe you can Create CustomView with ImageView And Transparent label with numberOflines more than two or whatever you want to restrict it to , then replace the navigation back button with That Barbutton initiated with CustomVIew, That Can Solve your problem,, Hope fully

Adding Custom UIButton To subView

I have subview which it initiated by touch on the UIbutton in the main view.
Once the subview pops up it displays a label with the info I provided. This all works. I just need an UIbutton to show up so I can then set it up to dismiss the subview and go back to the main view. i have searched all over and have found nothing that helps.
Here is what my code in my .m file looks like:
////Button that Displays Subview with Its Label and Button
- (IBAction)showInfo:(id)sender
/////UI Subview
{UIView *mySubview = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 480)];
[self.view addSubview:mySubview];
mySubview.backgroundColor = [UIColor blackColor];
mySubview.alpha = .7f;
//////Label in SubView
{UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 50)];
label.text = #"Here is info";
label.textColor = [UIColor whiteColor];
label.backgroundColor= [UIColor clearColor];
[self.view addSubview:label];
////Button in Subview
//create the button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"button-info-x.png"] forState:UIControlStateNormal];
//set the position of the button
button.frame = CGRectMake(120, 252, 68, 68);
//add the button to the view
[self.view addSubview:button];
Now I just need to add an action to the UIButton to dismiss the Subview?
First Take IBOutlet of subView and add it to the main View.
IBOutlet UIView *subView;
Then, add UIButton to the SubView like this:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//set the position of the button
button.frame = CGRectMake(0, 0, 100, 30);
//set the button's title
[button setTitle:#"Click Me!" forState:UIControlStateNormal];
[btnMenu addTarget:self action:#selector(your MethodName:) forControlEvents:UIControlEventTouchUpInside];
//add the button to the view
[subView addSubview:button];
Then,
-(IBAction)your MethodName:(id)sender {
}
In Above Method Remove SubView from Main View.
If you're simply looking to set an image for a UIButton instead of a title, you're looking for the - (void)setImage:(UIImage *)image forState:(UIControlState)statemethod.
You should check the UIButton reference for more info.
Add Target to the custom button
{
.....
[button addTarget:self action:#selector(your dismiss:) forControlEvents:UIControlEventTouchUpInside];
.......
}
-(IBAction)your dismiss:(id)sender
{
// write the dismissal code here
}

UIButton in UIView in UITableView = can't click the button

If I add the button straight everything goes fine. I'd really like to add it inside a view and still be able to click it. Here's the code:
UIView *containerView =
[[[UIView alloc]
initWithFrame:CGRectMake(0, 0, 300, 60)]
autorelease];
UIButton *footerButton = [UIButton buttonWithType:UIButtonTypeCustom];
footerButton.frame = CGRectMake(10, 10, 300, 40);
[footerButton addTarget:self action:#selector(click) forControlEvents:UIControlEventTouchUpInside];
[containerView addSubview:footerButton];
Did you set the footer height to the height of the view you are adding to it? I had a similar problem when I returned a UIView containing a UIButton in the method viewForFooterInSection. The footer height was not large enough until I updated the heightForFooterInSection method. For example:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return containerView.bounds.size.height;
}
All works fine! In your TableViewController do:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)] autorelease];
UIButton *footerButton = [UIButton buttonWithType:UIButtonTypeCustom];
footerButton.frame = CGRectMake(10, 10, 300, 40);
[footerButton addTarget:self action:#selector(click) forControlEvents:UIControlEventTouchUpInside];
[containerView addSubview:footerButton];
[footerButton setTitle:#"Touch me!" forState:UIControlStateNormal];
containerView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
self.tableView.tableFooterView = containerView;
}
- (void)click {
NSLog(#"I am here!");
}
This #selector(click) looks a little odd. I would have thought your click function would like something like:
- (void)click:(id)sender;
If that's what you have then you need to add the colon #selector(click:) to make the signatures match.

can't click UIButton when it's added to UIImageView

guys, i want to click my uiButton after it's added to UIImageVIew, but it doesn't work.
this is my code :
UIButton *btnDetail = [[UIButton buttonWithType:UIButtonTypeDetailDisclosure]retain];
btnDetail.frame = CGRectMake(0,0,100,100);
[btnDetail addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventAllTouchEvents];
[self.imageView addSubview:btnDetail];
the button can't click when i add it to UIImageVIew, but if i don't add it to UIImageView, it works properly.
please somebody help me
Note: By default the UserInteraction property of UIImageView is set to NO. This the place where most of us makes mistake.
So the main thing to check in while adding any control to UIImageView is to set its UserInteractionEnabled property to YES.
[self.imageView setUserInteractionEnabled:YES];
So modify your code as below:
UIButton *btnDetail = [[UIButton buttonWithType:UIButtonTypeDetailDisclosure]retain];
btnDetail.frame = CGRectMake(0,0,100,100);
[btnDetail addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventAllTouchEvents];
[self.imageView addSubview:btnDetail];
[self.imageView bringSubviewToFront:btnDetail];
[self.imageView setUserInteractionEnabled:YES];
HAppy Coding...
UIImageView has userInteractionProperty set to NO by default so it does not handle touches and does not propagate them to its subviews. Try to set it to YES:
self.imageView.userInteractionEnabled = YES;
hey i had use this code. its working properly
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 210.0, 100.0, 20.0);
[button addTarget:self action:#selector(show) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"ShowView" forState:UIControlStateNormal];
[image2 addSubview:button];
[image2 bringSubviewToFront:button];
[image2 setUserInteractionEnabled:YES];
If someone has interaction problem with UIButton in UIImageView do next steps.
1 Create property of UIImageView:
#property (nonatomic, strong) UIImageView *buttonImageView;
2 Than synthesize it:
#synthesize buttonImageView = _buttonImageView;
3 Create implementation method:
- (UIImageView *) buttonImageView {
_buttonImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[_buttonImageView setBackgroundColor:[UIColor whiteColor]];
[_buttonImageView setUserInteractionEnabled:YES];
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[addButton setTitle:#"add button" forState:UIControlStateNormal];
addButton.frame = CGRectMake(0, 0, 160, 50);
[addButton setUserInteractionEnabled:YES];
[addButton setEnabled:YES];
[addButton setAlpha:1];
[addButton addTarget:self action:#selector(addNewImage) forControlEvents:UIControlEventTouchUpInside];
return _buttonImageView;
}
4 For example in viewDidLoad method add subview to your view:
[self.view addSubview:self.buttonImageView];