How do I programmatically create and position a button in a macOS Cocoa application?
Asked
Active
Viewed 2.0k times
2 Answers
19
To possition button You need to change the button's origins x and y. Look at the sample code which I wrote below and comments.
You can do it like this:
-(void)awakeFromNib {
//Start from bottom left corner
int x = 100; //possition x
int y = 100; //possition y
int width = 130;
int height = 40;
NSButton *myButton = [[[NSButton alloc] initWithFrame:NSMakeRect(x, y, width, height)] autorelease];
[[windowOutlet contentView] addSubview: myButton];
[myButton setTitle: @"Button title!"];
[myButton setButtonType:NSMomentaryLightButton]; //Set what type button You want
[myButton setBezelStyle:NSRoundedBezelStyle]; //Set what style You want
[myButton setTarget:self];
[myButton setAction:@selector(buttonPressed)];
}
-(void)buttonPressed {
NSLog(@"Button pressed!");
//Do what You want here...
}
** WindowOutlet is window so don't forget to IBOutlet it.

Justin Boo
- 10,132
- 8
- 50
- 71
0
All buttons are controls and all controls are views, so see, in order:

Peter Hosey
- 95,783
- 15
- 211
- 370
-
9You should never link someone to apple documentation as an answer. It's never the answer. No one learns or understands anything in this format. – chrisallick Nov 17 '15 at 23:53