iPhone/iPad UIButton TitleLabel text not appearing - cocoa-touch

I created a grid of buttons. The following code creates the buttons and displays them, but there is no text on the button. Is there a setting I am missing? (Obj-C replies are fine, I'm bi-lingual)
RectangleF frame = new RectangleF (X + 3, Y + 3, cellWidth - 2, cellHeight - 2);
UIButton button = new UIButton (frame);
button.TitleLabel.Text = "Baha'i";
button.TitleLabel.Font = UIFont.FromName ("Helvetica-Bold", 15);
button.TitleLabel.TextColor = UIColor.Black;
button.TitleLabel.Frame = frame;
button.BackgroundColor = UIColor.FromWhiteAlpha(.5f,.5f);
this.AddSubview (button);

I think you want setTitle: forState:
[button setTitle:#"Baha'i" forState:UIControlStateNormal]

A UIButton inherits from UIView, so another way to add text and images, is to add subview. Example:
// My Image
UIImage *buttonImage = [UIImage imageNamed:#"myImage.png"];
UIImageView *buttonImageView = [[[UIImageView alloc]
initWithFrame:CGRectMake(0, 0,
buttonImage.size.width,buttonImage.size.height)] autorelease];
[buttonImageView setImage:buttonImage];
// My Label
UILabel* titleLabel = [[[UILabel alloc]
initWithFrame:CGRectMake(0, 0,
buttonImage.size.width, buttonImage.size.height)] autorelease];
titleLabel.text = #"My Text";
titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 11.0];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = UITextAlignmentCenter;
// Create Button with Image and Label
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addSubview:buttonImageView];
[button addSubview:titleLabel];

UIButton * selectCountryBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[selectCountryBtn setTitle:#"My Title" forState:UIControlStateNormal];
Here, I have create sample programmatically button, and then set the title for its Normal Control state, You can use your own button object for set the title string, additionally you can also set title text for another control states by change UIControlStateNormal to another required states.

In my case (Swift 4) it was the following:
btnLogin.setTitle("Welcome, " + var_name, for: [])

For swift Developers-
button.setTitle("Your button Name", for: .normal)

self.ButtonName.setTitle("Here Put Your variable model", for: .normal)

self.Button_name.titleLabel.text = #"Your title name";

Related

Objective-c - Border is over other view

I am trying to put a UILabel over my custom button. The problem is: when I add this label, it is under my button border, I want it over the border.
This is the image of my problem:
(source: abril.com)
.
and this is the code:
//#define DEFAULTCOLOR [UIColor colorWithRed:1 green:161.f/255.f blue:54.f/255.f alpha:1]
UIButton *banner = [UIButton buttonWithType:UIButtonTypeRoundedRect];
banner.frame = CGRectMake(45, 45, 230, 190);
[[banner layer] setBorderWidth:3.0f];
[[banner layer] setBorderColor:DEFAULTCOLOR.CGColor];
[self.view addSubview:banner];
UILabel *overButtonLabel = [[UILabel alloc]initWithFrame:CGRectMake(-10, -10, 168, 20)];
overButtonLabel.backgroundColor = DEFAULTCOLOR;
overButtonLabel.text = #"Testing";
float widthIs = [overButtonLabel.text boundingRectWithSize:overButtonLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:overButtonLabel.font }
context:nil].size.width;
overButtonLabel.frame =CGRectMake(-10, -10, widthIs, 20);
overButtonLabel.font = [UIFont fontWithName:#"OpenSans-Bold" size:15];
overButtonLabel.textColor = [UIColor whiteColor];
[banner addSubview:overButtonLabel];
[banner bringSubviewToFront:overButtonLabel];
Regards!
You cannot do that as per CALayer class reference border are always draw above contents:
https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/CALayer_class/Introduction/Introduction.html#//apple_ref/occ/instp/CALayer/borderWidth
You can do one thing take a view and add both button and label in that view.
In that view your label must be on the front.

how to create button from title string

I want create UIButton from NSString.
I have one string like this #"First Button" I want first get size of width pixel and after create one Button According to this string but I don't know about it.
please guide me.
You can get the CGSize of NSString using sizeWithAttributes (before we used sizeWithFont but this is now deprecated method with iOS 7) and then create UIButton according to the size like
NSString *string = #"First Button";
CGSize size = [string sizeWithAttributes:
#{NSFontAttributeName:
[UIFont systemFontOfSize:27.0f]}];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 50, size.width, size.height);
button.titleLabel.textColor = [UIColor blackColor];
[button setTitle:string forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
Review this working fine for me.
Hope this will help you.
First you have to get the size of the text by using
NSString someText = #"some Text";
CGSize constraintSize = CGSizeMake(youMaxWidthForButton, youMaxHeightForButton);
CGRect labelSize = [someText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]} context:nil];
than you create your UIButton
UIButton *button = [[UIButton alloc]initWithFrame:labelSize];
finally you set the button title
button.titleLabel.text = someText;

iOS 7 BarButtonItem with image and title

I'm trying to figure out how can I achieve something like this:
This is a toolbar and I'd like to keep the button title text without having to create the whole image with icon AND text. How can I add the icon to the left of the UIBarButtonItem while keeping the text set with:
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Button" style:UIBarButtonItemStyleBordered target:nil action:nil];
EDIT
This is what I achieved with the following code:
UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"Test"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
customButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
[customButton sizeToFit];
UIBarButtonItem *customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
Two issues here: the first is the size of the UIButton and the second is that, as you can see from the gif, the button doesn't animate properly when I tap inside the button and when I release the tap. Any ideas?
You can embed a UIButton as a custom view inside your UIBarButtonItem. You can create your UIButton however you want, including with an image and text, using -setImage:forState: and -setTitle:forState:.
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom];
[customButton setImage:[UIImage imageNamed:#"image"] forState:UIControlStateNormal];
[customButton setTitle:#"Button" forState:UIControlStateNormal];
[customButton sizeToFit];
UIBarButtonItem* customBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customButton];
self.navigationItem.leftBarButtonItem = customBarButtonItem; // or self.navigationItem.rightBarButtonItem
Note that when doing this, you'll need to attach your IBAction methods to customButton, not to customBarButtonItem.
For more info, see the documentation for initWithCustomView:.
You can also do all of this in interface builder just by dragging a UIButton to the left bar button/right bar button slot on a navigation bar.
I was not satisfied with all solutions found on stack overflow becauseI like how UIBarButtonItenm convert images so they are displayed correctly and they can be changed with tint colour. So i discovered this solution that I can use nicely with not much code... End effect is similar to toolbar in facebook and other current apps...
When you change tint colour of view contained in UIBArButtonItem colours of image and title change accordingly, really cool , I do not have to create special images at all.
This code is called from each button like that Competition Button, and also Button is set as referencing outlet...
- (void)selectButton:(UIButton *)sender {
_competitionButton.superview.tintColor = [UIColor lightGrayColor];
_usersButton.superview.tintColor = [UIColor lightGrayColor];
_managementButton.superview.tintColor = [UIColor lightGrayColor];
sender.superview.tintColor = [UIColor whiteColor];
}
- (IBAction)onCompetitionButtonClick:(UIButton *)sender {
[self selectButton:sender];
[_scrollView scrollToPage:0 of:3];
}
In Button like that titled Competition there is only title and in bar button item there is image... This is how I have setup it and it works , maybe there are also other possibilities..
So I managed to do my solution programatically... Some users where complaining it does not work ... So how to create UTToolbar with image and item so that you can change color of button by tint and it magically alters image as well as title label ? My UI editor solution works for sure...
In this code can clarify things more and you can do it programatically either...
- (void)loadToolbar {
NSMutableArray *items = NSMutableArray.new;
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
for (uint pageIndex = 0; pageIndex < _controllers.count; ++pageIndex) {
UIView *itemView = [UIView.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemView.backgroundColor = [UIColor clearColor];
itemView.tintColor = [UIColor orangeColor];
[itemView addSubview:[self createToolbarForItemView:pageIndex]];
[itemView addSubview:[self createButtonForItemView:pageIndex]];
UIBarButtonItem *item = [UIBarButtonItem.alloc initWithCustomView:itemView];
item.style = UIBarButtonItemStylePlain;
[items add:item];
[items add:[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]];
}
[_toolbar setItems:items];
}
- (UIButton *)createButtonForItemView:(uint)pageIndex {
UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeSystem];
itemButton.frame = CGRectMake(0, 0, 100, 44);
itemButton.titleLabel.font = [UIFont systemFontOfSize:11];
itemButton.contentEdgeInsets = UIEdgeInsetsMake(30, 0, 0, 0);
itemButton.text = [_controllers[pageIndex] tabTitle];
itemButton.touchUp = ^(UIButton *sender) {
for (UIButton *button in _buttons) button.superview.tintColor = UI.toolBarInactiveButtonTextColor;
sender.superview.tintColor = UI.toolBarActiveButtonTextColor;
[self showPage:pageIndex];
};
[_buttons add:itemButton];
return itemButton;
}
- (UIToolbar *)createToolbarForItemView:(uint)pageIndex {
UIToolbar *itemToolbar = [UIToolbar.alloc initWithFrame:CGRectMake(0, 0, 100, 44)];
itemToolbar.tintColor = nil;
itemToolbar.barStyle = _toolbar.barStyle;
itemToolbar.translucent = _toolbar.translucent;
UIBarButtonItem *imageItem = [_controllers[pageIndex] tabImageItem];
imageItem.style = UIBarButtonItemStylePlain;
imageItem.tintColor = nil;
imageItem.imageInsets = UIEdgeInsetsMake(-10, 0, 0, 0);
itemToolbar.items = #[
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil],
imageItem,
[UIBarButtonItem createWithItem:UIBarButtonSystemItemFlexibleSpace :nil :nil]
];
return itemToolbar;
}
I solved this problem as follows:
[Button **setTitleColor**:[UIColor colorWithRed:129/255.0f green:124/255.0f blue:110/255.0f alpha:1.0f] forState:**UIControlStateHighlighted**];

UIButton has gap

Making a UIButton. for some reason, it has a white gap around it (the grey area is the UIView the button is in):
code:
UIView *photoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, (THUMBNAIL_SIZE) + (PHOTO_VIEWER_OFFSET_COLUM_1 * 2))];
photoView.backgroundColor = [UIColor lightGrayColor];
UIScrollView *myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, photoView.frame.size.height)];
myScrollView.backgroundColor = [UIColor lightGrayColor];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(0, 0, 50, 50);
myButton.titleLabel.font = [UIFont fontWithName:labelFont size:16];
[myButton setTitle:#"X" forState:UIControlStateNormal];
[myButton setBackgroundImage:[UIImage imageNamed:#"add-report.png"] forState:UIControlStateNormal];
myButton.center = CGPointMake(((photoView.frame.size.width - myScrollView.frame.size.width) / 2) + myScrollView.frame.size.width, photoView.frame.size.height / 2);
[photoView addSubview:myButton];
[self.view addSubview:photoView];
I dont' want the white buffers space there, but i can't figure out how to get rid of it.
any ideas?
EDIT: if i try to change the background color:
myButton.backgroundColor = [UIColor orangeColor];
i get this effect:
It might be the text label that has a white background be default?
Try setting every color to [UIColor clearColor] such as button.background and button.titleLabel.background.
Also try to modify the image view. Maybe it does not scale automatically as expected:
button.imageView.contentMode = UIViewContentModeScaleToFill;

How can I have a UIBarButtonItem with both image and text?

When I try to use an image for a UIBarButtonItem, the text isn't shown. Is there a way to show both the text and the image?
You can init the UIBarButtonItem with a custom view that has both image and text. Here's a sample that uses a UIButton.
UIImage *chatImage = [UIImage imageNamed:#"08-chat.png"];
UIButton *chatButton = [UIButton buttonWithType:UIButtonTypeCustom];
[chatButton setBackgroundImage:chatImage forState:UIControlStateNormal];
[chatButton setTitle:#"Chat" forState:UIControlStateNormal];
chatButton.frame = (CGRect) {
.size.width = 100,
.size.height = 30,
};
UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:chatButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];
I suggest a way how to do this using Storyboard:
Drag and drop to ToolBar usual UIView. It automatically will be wrapped to Bar Button Item. Adjust View width in "Size inspector". Change background color of View to clear color.
Put UIButton and UILabel inside a View. You can use constraints to adjust their positions. Also you can put thier outside of a View, for example, little higher or less (like on my picture). Put Default and Highlighted images for UIButton.
Copy Bar Button Item and adjust another buttons. Add Flexible spaces.
Create outlets.
Done :). When you run app, you get Tool Bar like this:
P.S. Here you can read how to create UIToolbar subclass using .xib
Swift 4.2 with target
extension UIBarButtonItem {
convenience init(image :UIImage, title :String, target: Any?, action: Selector?) {
let button = UIButton(type: .custom)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.frame = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
if let target = target, let action = action {
button.addTarget(target, action: action, for: .touchUpInside)
}
self.init(customView: button)
}
}
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:#"image.png"] forState:UIControlStateNormal];
[button addTarget:target action:#selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 53, 31)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
[label setFont:[UIFont fontWithName:#"Arial-BoldMT" size:13]];
[label setText:title];
label.textAlignment = UITextAlignmentCenter;
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
[button addSubview:label];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = barButton;
Kris Markel's answer is a good start (only < iOS7), but if you use tint color, it wount work for the image and the highlighted state of the button.
I've created a category that will create a UIBarButtonItem (leftBarButtonItem) that looks and behaves like a normal iOS7 back button. Have a look at: https://github.com/Zero3nna/UIBarButtonItem-DefaultBackButton
Swift Update for UIBarButtonItem with a custom view that has both image and text.
var chatImage: UIImage = UIImage(named: "YourImageName")
var rightButton : UIButton = UIButton(type: UIButtonType.custom)
rightButton.setBackgroundImage(rightImage, for: .normal)
rightButton.setTitle(title, for: .normal)
rightButton.frame.size = CGSize(width: 100, height: 30)
let menuUIBarButtonItem = UIBarButtonItem(customView: rightButton)