Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone/iPad UIButton TitleLabel text not appearing

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);
like image 607
Ian Vink Avatar asked Mar 07 '10 02:03

Ian Vink


2 Answers

I think you want setTitle: forState:

[button setTitle:@"Baha'i" forState:UIControlStateNormal]
like image 185
Tobias Cohen Avatar answered Nov 01 '22 03:11

Tobias Cohen


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];
like image 33
ddiego Avatar answered Nov 01 '22 03:11

ddiego