Cocoa_Basic
Cocoa_Basic
Using NSButton
NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(20, 100, 100, 30)];
[button setTitle:@"Click Me!"];
[button setTarget:self];
[button setAction:@selector(buttonClicked:)];
[self.window.contentView addSubview:button];
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Code to initialize application
}
Creating a Simple UI
import Cocoa
view.addSubview(label)
self.view = view
}
}
// ViewController.swift
import Cocoa
// ViewController.swift
import Cocoa
let constraints = [
label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 50)
]
NSLayoutConstraint.activate(constraints)
advertisement
Understanding NSApplication Tutorial
NSApplication is the central class responsible for managing the application's event loop and the
application's interaction with the macOS operating system. It handles the app's lifecycle, including its
launching, running, and termination, while providing access to the shared application instance and
managing the app's windows and menus. Understanding NSApplication is crucial for creating
responsive and functional macOS applications using the Cocoa framework.
Copy
Basic NSApplication Setup
import Cocoa
@main
class MyApp: NSApplication {
override func run() {
print("Application is running")
super.run()
}
}
@main
class MyApp: NSApplication {
override func applicationWillTerminate(_ notification: Notification) {
// Insert code here to tear down your application
print("Application will terminate")
}
}
Adding a Button
import Cocoa
window.makeKeyAndOrderFront(nil)
}
- (void)buttonClicked:(id)sender {
NSLog(@"Button was clicked!");
}
Responding to Key Events
- (void)keyDown:(NSEvent *)event {
NSString *characters = event.characters;
NSLog(@"Key pressed: %@", characters);
}
Searching in NSString
#import <Foundation/Foundation.h>
Using NSArray
NSArray *fruits = @[@"Apple", @"Banana", @"Cherry"];
for (NSString *fruit in fruits) {
NSLog(@"%s", [fruit UTF8String]);
}
Using NSDictionary
NSDictionary *person = @{ @"name": @"John", @"age": @30 };
NSLog(@"Name: %@, Age: %@", person[@"name"], person[@"age"]);