以编程方式在 macOS 应用程序中创建和定位 NSButton?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10251703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically create and position an NSButton in a macOS app?
提问by Matt Payne
How do I programmatically create and position a button in a macOS Cocoa application?
如何在 macOS Cocoa 应用程序中以编程方式创建和定位按钮?
回答by Justin Boo
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.
定位按钮 您需要更改按钮的原点 x 和 y。看看我在下面写的示例代码和注释。
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...
}
** WindowOutletis window so don't forget to IBOutlet it.
** WindowOutlet是窗口所以不要忘记 IBOutlet 它。
回答by Peter Hosey
All buttons are controls and all controls are views, so see, in order:
所有按钮都是控件,所有控件都是视图,因此请按顺序查看: