Jumhyn
Jumhyn

Reputation: 6777

UIView subviews not showing up

In my subclass of UIView (which I have instantiated in Interface Builder), has a couple buttons as subviews that I add to my view in the initWithCoder method like so:

theButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [theButton setFrame:CGRectMake([UIScreen mainScreen].bounds.size.height-150-10, 289, 150, 21)];
            [theButton.titleLabel setTextAlignment:UITextAlignmentRight];
            [theButton setOpaque:YES];
            [theButton.titleLabel setFont:[UIFont fontWithName:@"MyFont" size:32.0]];
            [theButton.titleLabel setTextColor:[UIColor redColor]];
            [theButton.titleLabel setText:@"text"];
            [self addSubview:theButton];
            [theButton addTarget:myTarget action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];

But the button will not draw as it is supposed to. If I set a breakpoint in drawRect:, and po [self subviews] with llvm, I get this output.

$0 = 0x0c93e860 <__NSArrayM 0xc93e860>(
<UIButton: 0xc93d910; frame = (10 289; 150 21); alpha = 0.5; layer = <CALayer: 0xc93d4a0>>,
<UIButton: 0xc93e2d0; frame = (408 289; 150 21); layer = <CALayer: 0xc93e390>>
)

So why isn't my button showing up?

Edit: my superview's recursiveDescription:

<UIView: 0xa46b220; frame = (0 0; 320 568); transform = [0, -1, 1, 0, 0, 0]; autoresize = RM+BM; layer = <CALayer: 0xa46b280>>
   | <MyView: 0xa168710; frame = (0 0; 568 320); autoresize = W+H; layer = <CALayer: 0xa1687d0>>
   |    | <UIButton: 0xa16c160; frame = (10 289; 150 21); alpha = 0.5; layer = <CALayer: 0xa16bcc0>>
   |    |    | <UIButtonLabel: 0xa16c3e0; frame = (0 0; 0 0); clipsToBounds = YES; hidden = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xa16c480>>
   |    | <UIButton: 0xa16cb00; frame = (408 289; 150 21); layer = <CALayer: 0xa16cbc0>>
   |    |    | <UIButtonLabel: 0xa16c7e0; frame = (0 0; 0 0); clipsToBounds = YES; hidden = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xa16c880>>

Upvotes: 0

Views: 1061

Answers (2)

Scott Berrevoets
Scott Berrevoets

Reputation: 16946

Instead of calling setText on the button's label, try sending setTitle:forState to the button (not its title label) instead:

[theButton setTitle:@"text" forState:UIControlStateNormal]

Upvotes: 0

Wim Haanstra
Wim Haanstra

Reputation: 5998

Well, my guess is that your button is showing up, but you made it a custom button with no text for the normal state (and because you are not using any background image or color, it seems invisible).

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"Text" forState:UIControlStateNormal];

Upvotes: 2

Related Questions