Why doesn't this UIButton show its text label? - iphone

Everything about this UIButton renders great except the text that's supposed to be on it. NSLog demonstrates that the text is in the right place. What gives?
UIButton *newTagButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[newTagButton addTarget:self action:#selector(showNewTagField) forControlEvents:UIControlEventTouchUpInside];
newTagButton.titleLabel.text = #"+ New Tag";
NSLog(#"Just set button label to %#", newTagButton.titleLabel.text);
newTagButton.titleLabel.font = [UIFont systemFontOfSize:17];
newTagButton.titleLabel.textColor = [UIColor redColor];
CGSize addtextsize = [newTagButton.titleLabel.text sizeWithFont:[UIFont systemFontOfSize:17]];
CGSize buttonsize = { (addtextsize.width + 20), (addtextsize.height * 1.2) };
newTagButton.frame = CGRectMake(x, y, buttonsize.width, buttonsize.height);
[self.mainView addSubview:newTagButton];

There are a set of APIs on UIButton that should be used to change those properties.
The titleLabel can and will be changed by the UIButton internally.
[button setTitle:title forState:state];
[button setTitleColor:color forState:state];
[button setTitleShadowColor:color forState:state];
You should always set these properties through these methods (when available) rather than touching the titleLabel directly. For fonts you can change it on the titleLabel directly since they don't provide a method on UIButton.

Related

How to add a button in UIScrollView with addSubview?

I am new to iOS development and I have a problem with UIScrollView. First of all, I've created a Scroll View in a storyboard and added
#property (retain, nonatomic) IBOutlet UIScrollView *mainScroll;
in view controller handler
In the viewDidLoad method I have the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
self.mainScroll.contentSize = CGSizeMake(100.0,100.0); // Have to set a size here related to your content.
// You should set these.
self.mainScroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.mainScroll.minimumZoomScale = .5; // You will have to set some values for these
self.mainScroll.maximumZoomScale = 2.0;
self.mainScroll.zoomScale = 1;
UIButton* b = [[UIButton alloc] init];
[b setBounds:CGRectMake(.0f,0.f,100.0,100.0)];
[self.mainScroll addSubview:b];
}
But the button does not appear in the simulator. However if I add a button on storyboard in the IB, the button appears and I can scroll the view.
How can I add the button in code?
Try this code
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.mainScroll addSubview:button];
bounds and frame are not the same thing.
Use this code instead...
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, 100, 44);
[self.mainScroll addSubview:button];
You need to set scroll view contents size, something like the following code.
[self.mainScroll setContentSize:CGSizeMake(width, height)];
Try this :
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(self.mainScroll.frame.origin.x + 25 ,self.mainScroll.frame.origin.y +25, 50, 44);
[self.mainScroll addSubview:button];
Best and easiest way to make a button from code is:
UIButton* yourButton = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
[yourButton setTitle:#"Your Title" forState:UIControlStateNormal];
// if you set the button's image the title won't be visible, because button's title is "under" the image. I recomend you to use this if you have a cut and dried image.
[yourButton setImage:[UIImage imageNamed:#"yourImage.png"] forState:UIControlStateNormal];
// if you set the button's background image, button's title will be visible
[yourButton setBackgroundImage:[UIImage imageNamed:#"yourBackgroundImage.png"] forState:UIControlStateNormal];
// you can add target to the button, for handle the event when you touch it.
[yourButton addTarget:self action:#selector(handleToucUpInside:) forControlEvents:UIControlEventTouchUpInside];
// then add the button
[self.view addSubview:yourButton];
- (void) handleToucUpInside:(id)sender{
// here you can do anything you want, to handle the action
}

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 UIButton to UIScrollView issue

I am trying to add a bunch of UIButton to a horizontal UIScrollView using the following code, however I am not seeing anything and all I see is just a white UIScrollBar. Why is this? I am pretty sure that I messed up something as before it was just working just fine.
self.category = [[NSArray alloc]initWithObjects:#"ALL", #"FOOD",#"NIGHT LIFE",#"ARTS & ENTERTAINMENT",#"SPORT", #"SHOP", #"COLLEGE & UNIVERSITY", #"TRAVEL SPOT", nil];
self.scrollView.delegate = self;
self.scrollView.scrollEnabled = YES;
self.scrollView.autoresizingMask = YES;
int xOffset = 0;
for(int index=0; index < [self.category count]; index++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button.titleLabel setTextAlignment:UITextAlignmentCenter];
[button setBackgroundImage:[UIImage imageNamed:#"CategoryTab.png"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTag:index];
[button addTarget:self action:#selector(pressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[self.category objectAtIndex:index] forState:UIControlStateNormal];
[button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[button.titleLabel setFont:[UIFont fontWithName:#"bebas" size:15.0]];
CGSize maximumLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [[self.category objectAtIndex:index] sizeWithFont:[UIFont fontWithName:#"ArialMT" size:15.0]
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
[button setFrame: CGRectMake(xOffset, 0, expectedLabelSize.width + 30, 38)];
[self.scrollView addSubview:button];
xOffset += expectedLabelSize.width + 30;
[button release];
}
self.scrollView.contentSize = CGSizeMake(xOffset, 38);
A few possible causes :
The UIButton is released once too often. It's created autoreleased, then added to the scrollview, then released, which effectively means it will be dealloc'd when the autorelease pool ends. I'm surprised this does not crash, actually. Are you using Automatic Reference Counting?
is self.scrollview correctly initialized? If it's nil, it will simply fail silently.
is the "bebas" font really loaded and available? Custom font loading isn't that trivial on iOS.
Also :
You're not using the actual button font to measure the label size. ("bebas" vs "ArialMT")
you probably have a leak on line 1. That NSArray would better be autoreleased ( using[NSArray arrayWithObjects:...]).
autoresizingMask is not a BOOL value, it's an OR combination of flags.

iPhone - custom chevron icon

Is it possible to swap out the icon for UITableViewCellAccessoryDetailDisclosureButton with a custom icon?
Sure. Set the accessoryView to a custom image view.
Use this in viewForAnnotation:
UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeCustom];
advertButton.frame = CGRectMake(0, 0, 23, 23);
advertButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
advertButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
[advertButton setImage:[UIImage imageNamed:#"button-image.png"] forState:UIControlStateNormal];
[advertButton addTarget:self action:#selector(advertFunction:) forControlEvents:UIControlEventTouchUpInside];
annView.rightCalloutAccessoryView = advertButton;
Dont forget to include the image in your app and the function the selector is assigned too.