views:

13761

answers:

1

Hi, I'm learning how to develop on the iPhone, I bought a book called Beginning iPhone 3 development Exploring the SDK. After I bit I decided to ditch Interface Builder. I still design all my views in IB, but I write It all in code and only use the nib file to get the controls' frames.

So now I need to make a UIButton, and the documentation is different from the other controls. I tried using initWithFrame, and theres this other method buttonWithType which I assume is autoreleased, but anyway I couldn't get a button to appear on the screen. Could someone please write a bit of code that locally creates a button with a title I can change that I can then just add to my views subview and release so I can see how it's done?

Thanks!!

+12  A: 

I'd try something like this:

    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(20, 20, 200, 44); // position in the parent view and set the size of the button
    [myButton setTitle:@"Click Me!" forState:UIControlStateNormal];
    // add targets and actions
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // add to a view
    [superView addSubview:myButton];

Disclaimer: Just typing this in here. I don't have access to my Mac at the moment so I can't test it.

P.S. Any particular reason not to use Interface Builder? Just curious.

Thomas Müller
Assuming the selector `buttonClicked:` exists, this is perfectly valid and a good way to go about it. +1
Tim
I don't like IB because its like a big black box and I can't see what's going on and it just complicates things... Only thing I think its useful for is designing the interface.Is this myButton autoreleased? Would it also works if I didUIButton *myButton = [[UIButton alloc] initWithFrame:...];.. but then how would I set the readonly button type..
Mk12
And couldn't I do myButton.titleLabel.text = @"Click Me!" instead of setTitle forState?
Mk12
The buttonType is a read only property. I'm not sure what type of button you'd get if you initWithFrame:, and you won't be able to change it later. You could try it and see what the buttonType property is, but it's probably safer to go with buttonWithType:.Yes, this button would be autoreleased.Not sure about setting myButton.titleLabel.text. If you later want to add different titles for different states I guess you'd have to change the code then. I'd only use myButton.titleLabel for modifying the styling of the button, like color, font and font size.
Thomas Müller
And if I do [myButton retain] it will act as a normal object that I am responsible for releasing correct?
Mk12
Yes.If you just want to add it to your view you wouldn't need to retain the button, though. Your superView would do that when you call [superView addSubview:myButton];
Thomas Müller
Ok thanks!
Mk12
it's CGRectMake
PeanutPower
Thanks, I fixed my answer
Thomas Müller