I am building an OS X desktop app that allows a user to select an item from a dropdown. I am trying to create an NSPopupButton menu like the response to this question, which is also very similar to this tutorial, but when I build and run in Xcode, I get an EXC_BAD_INSTRUCTION error and the NSPopupButton evaluates to nil in the debugger. Did I miss a step initializing the menu? I also have a text input, but it works just fine. My code:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var textInput: NSTextField!
#IBOutlet weak var myMenu: NSPopUpButton!
// other stuff here for processing textInput
#IBAction func selectFromMyMenu(sender: NSPopUpButton) {
let selection = myMenu.titleOfSelectedItem
if selection == "Second Option" {
// do something
} else {
// do something else - first option is default
}
}
func setupMyMenu() {
let menuItems = ["First Option", "Second Option"]
myMenu.removeAllItems()
myMenu.addItemsWithTitles(menuItems)
myMenu.selectItemAtIndex(0)
}
override func viewDidLoad() {
super.viewDidLoad()
setupMyMenu()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Try reconnecting your button from the storyboard to your ViewController code.
Related
I am new to Mac OSX and with Apple promoting the fact that the bodies of code are becoming similar decided to tell the folk I am writing code for we should be able to do a Mac OSX version. iPhone and iPad versions are all good and about to release second version so no issues there.
So I am subclassing NSWindowController to get access to the Toolbar and worked out how to remove and add items on the toolbar, but for the life of me I can not get one NSViewController (firstViewController) to dismiss and bring up the second NSViewController (secondViewController) in the same NSWindowController.
So the 2 issues are that
1. I want to be able to performSegueWithIdentifier from the first NSViewController in code and
2. bring up the second NSViewController by replacing the first NSViewController in the same NSWindowController.
If I add a button to the firstViewController and put a segue to the secondViewController then when I select the button the secondViewController comes up just fine but in a seperate window not the same NSWindowController that I want it to and the firstViewController does not get replaced but stays in the NSWindowController.
So I know the segue idea will work but its not working in code and when I do insert the segue from a button it works but into a seperate NSViewController that is not part of the NSWindowController.
I am trying to find some programming guide from Apple on the issue but no luck so far.
Here is an overview from my Storyboard:
Here is my NSWindowController subclassed and the func loginToMe2Team is trigger from the NSToolBar and its working just find as the print statements show up on the console.
import Cocoa
class me2teamWindowsController: NSWindowController {
#IBOutlet var mySignUp : NSToolbarItem!
#IBOutlet var myToolbar : NSToolbar!
let controller = ViewController()
override func windowDidLoad() {
super.windowDidLoad()
print("window loaded")
}
override func windowWillLoad() {
print("window will load")
}
#IBAction func logInToMe2Team(sender: AnyObject){
controller.LogIn() //THIS IS THE FUNC I AM TESTING WITH
}
#IBAction func signUpToMe2Team(sender: AnyObject){
controller.signUp()
}
Here is my NSViewController subclassed with the func LogIn. Its getting selected just fine but the performSegueWithIdentifier is not. And I did cut and past the Identifier to make absolutely sure it was the same.
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var theWebPage: WebView!
#IBOutlet weak var progressIndicator: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://thewebpage.com.au"
self.theWebPage.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
}
override func viewDidAppear() {
}
func LogIn() {
print("I logged in")
self.performSegueWithIdentifier("goToTeamPage", sender: self)
//THIS IS THE BIT THATS NOT WORKING
}
func signUp() {
print("I have to sign up now")
}
override var representedObject: AnyObject? {
didSet {
}
}
func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!)
{
self.progressIndicator.startAnimation(self)
}
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!)
{
self.progressIndicator.stopAnimation(self)
}
}
You need to use a custom segue class (or possibly NSTabViewController if it’s enough for your needs). Set the segue’s type to Custom, with your class name specified:
…and implement it. With no animation, it’s simple:
class ReplaceSegue: NSStoryboardSegue {
override func perform() {
if let src = self.sourceController as? NSViewController,
let dest = self.destinationController as? NSViewController,
let window = src.view.window {
// this updates the content and adjusts window size
window.contentViewController = dest
}
}
}
In my case, I was using a sheet and wanted to transition to a different sheet with a different size, so I needed to do more:
class ReplaceSheetSegue: NSStoryboardSegue {
override func perform() {
if let src = self.sourceController as? NSViewController,
let dest = self.destinationController as? NSViewController,
let window = src.view.window {
// calculate new frame:
var rect = window.frameRectForContentRect(dest.view.frame)
rect.origin.x += (src.view.frame.width - dest.view.frame.width) / 2
rect.origin.y += src.view.frame.height - dest.view.frame.height
// don’t shrink visible content, prevent minsize from intervening:
window.contentViewController = nil
// animate resizing (TODO: crossover blending):
window.setFrame(window.convertRectToScreen(rect), display: true, animate: true)
// set new controller
window.contentViewController = dest
}
}
}
I want to show/hide a window in swift by clicking a button from main window. Beginsheet is showing the window, but endsheet is not closing the window. My appdelegate code is given:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
var settingsController: SettingsController?
#IBAction func inSettings(sender: NSObject?)
{
settingsController = SettingsController(windowNibName: "SettingsController")
window.beginSheet(settingsController!.window!, completionHandler: nil)
}
#IBAction func outSettings(sender: NSObject?)
{
window.endSheet(settingsController!.window!)
}
}
SettingsController:
import Cocoa
class SettingsController: NSWindowController {
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
Swift 3 Solution:
Lets say that you have WindowA and WindowB. You want to open WindowB but first You want to hide WindowA.
Connect windows with a segue. (Select "Show" as segues "Kind" property) And you need a static class to keep hidden window. in WindowA override shouldPerformSegue and keep WindowA as a static NSWindow object.
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
YourStaticClass.WindowA = self.view.window
self.view.window?.orderOut(self)
return true
}
orderOut(self) hides the window. Then WindowB will be opened.
In WindowB's view controller use a function to close windowB and show hidden WindowA:
#IBAction func btnBack_Click(_ sender: NSButton) {
YourStaticClass.WindowA?.makeKeyAndOrderFront(YourStaticClass.WindowA)
self.view.window?.close()
}
Use endSheet to end a document-modal sheet session. Like this:
#IBAction func outSettings(sender: NSObject?)
{
settingsController!.window!.endSheet(settingsController!.window!)
}
EDIT: You need to actually close the window in your completion handler you call orderOut, like this:
#IBAction func inSettings(sender: NSObject?)
{
settingsController = SettingsController(windowNibName: "SettingsController")
window.beginSheet(settingsController!.window!) {
settingsController!.window!.orderOut(nil)
}
}
I am trying to get a preview of my video device in a custom view.
But all I get is an empty window. I see that I have no problem accessing my camera. As soon as the app fires up i see my logitech cameras led turn on.
I assume my problem is adding the the preview layer as a sublayer.
Here is my simple code:
import Cocoa
import AVFoundation
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var video: NSView!
#IBOutlet weak var window: NSWindow!
let captureSession = AVCaptureSession()
var captureDevice : AVCaptureDevice?
var previewLayer : AVCaptureVideoPreviewLayer?
func applicationDidFinishLaunching(aNotification: NSNotification) {
captureSession.sessionPreset = AVCaptureSessionPresetLow
let devices = AVCaptureDevice.devices()
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
captureDevice = device as? AVCaptureDevice
println(captureDevice)
}
}
if captureDevice != nil {
beginSession()
}
}
func beginSession() {
println("begin")
var err : NSError? = nil
captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
if err != nil {
println("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.frame = self.video.bounds
previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
self.video.layer?.addSublayer(previewLayer)
captureSession.startRunning()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
Solved it.. At Interface Builder, I needed to add a custom view in core animation.
For my small swift-base AVFoundation grabber, this Q&A post helped me. I noticed that the following checks are important to make for the "Custom View" in the Interface builder:
Attribute Inspector > Check "Can Draw Concurrently":
View Effects Inspector > Check your custom view on the "Core Animation Layer list", (maybe even uncheck the main view controller)
In Swift 2 the error handling has changed. If you use Main.storyboard than the following approach should work:
class ViewController: NSViewController {
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var previewPanel: NSView!
override func viewDidLoad() {
super.viewDidLoad()
captureSession.sessionPreset = AVCaptureSessionPresetLow
let devices = AVCaptureDevice.devices()
for device in devices {
if (device.hasMediaType(AVMediaTypeVideo)) {
captureDevice = device as? AVCaptureDevice
//Swift.print("device: \(captureDevice)")
}
}
Swift.print("beginning")
do {
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(deviceInput)
// get the CustomView as preview panel
previewPanel = self.view.subviews.first
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.frame = self.view.bounds
// add layer to preview
previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
previewPanel.layer?.addSublayer(previewLayer!)
captureSession.startRunning()
} catch let error as NSError {
Swift.print("Error: no valid camera input in \(error.domain)")
}
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
Don't forget to add the CustomView.
I am trying to pass data between two viewContollers in an OS X storyboard application using Swift. When I press a button on VC1, it opens VC2, and prepareForSegue is run. However, I can't pass data back to VC1 because a. prepareForSegue isn't being run (because a window isn't being opened) and b. because even if it were, VC1 doesn't know data is being sent and I can't figure out a function (something like viewDidBecomeFocus, if such a function existed) to let it know to look. I feel like there must be a way to do this.
If you know of a way to do this in IOS but not OSX, it could still be useful.
Thanks!
Let assume that in your first ViewController you have one label and one button. When pressed, that button open popover (SecondViewController) with one textfield (and one button what says ready or close etc.), where you want take its value and assign it to your label. That is where delegates and protocols come handy.
SecondViewController:
#objc protocol TextDelegate {
func passedString(textValue: String)
}
class SecondViewController: NSViewController {
#IBOutlet weak var textField: NSTextField!
weak var delegate: TextDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
#IBAction func closePopOver(sender: AnyObject) {
if delegate != nil {
delegate!.passedString(textField.stringValue)
}
self.dismissViewController(self)
}
}
This is ViewController:
#IBOutlet weak var myLabel: NSTextField!
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "mySegue" {
let vc = segue.destinationController as! SecondViewController
vc.delegate = self
}
}
func passedString(textValue: String) {
myLabel.stringValue = textValue
}
My first question here. I'm making the jump from Delphi and Pascal to Xcode and Swift and feeling totally overwhelmed by the change.
I'm simply attempting to change the text of a label when a button is clicked. Here is my code from ViewController.swift
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var Label1: NSTextField!
#IBOutlet weak var ChangeText: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ButtonPressed(sender: AnyObject) {
Label1.stringValue = "Hello World"
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
When I run the application as soon as I click the button the application hangs.
I've also tried exchanging stringValue with text but NSTextField does not use this. I can't seem to make the label show up as UITextField.
What am I doing wrong?