Implement TouchBar functionality in Xcode Playgrounds - swift

How can I implement a NSTouchBar in using only Xcode Playgrounds? I realize that NSTouchBar, and its accompanying methods including makeTouchBar() are contained within the NSResponder class, which is the superclass of NSView, NSViewController, NSWindow, and SKView (a subclass of NSView.)
It is for this reason that I'm a little unsure how to approach access the TouchBar. There are so many subclasses of NSResponder I'm unsure as to which one is the correct one. And to my knowledge I cannot even access all of them, including the NSWindow for the Playground, which I suspect may be the one I need to access.
My current setup is:
let containerView = SKView()
PlaygroundPage.current.liveView = containerView
let containterScene = SKScene()
containerView.presentScene(containterScene)
And in checking the responder chain, for the SKView I get:
<SKScene> name:'(null)' frame:{{-250, -250}, {500, 500}} anchor:{0.5, 0.5}
And for the SKScene:
<SKView: 0x7fba36037a00>
<NSView: 0x7fba32d6fe80>
<PlaygroundViewBridgeService: 0x7fba32d569e0>
<NSNextStepFrame: 0x7fba32d76e20>
<NSWindow: 0x7fba32e177e0>
For some reason, the SKScene and SKView are not within the same chain, and I can't seem to access any responder higher than the SKView. Is there a way to extend the functionality of the already existing NSWindow?
Another problem is that many tutorials on using the TouchBar require access to the AppDelegate, which I don't think I have in Xcode Storyboards.
Any help implementing the TouchBar in Storyboards would be greatly appreciated.

The solution is actually quite simple. Create a custom subclass of NSViewController and implement the TouchBar override functions within it.
Then implement the above code:
let containerView = CustomSKView()
let containterScene = CustomSKScene()
containerView.presentScene(containerScene)
With the following additions.
let containerViewController = CustomNSViewController()
containerViewController.view = containerView
PlaygroundPage.current.liveView = containerViewController.view
This sets your custom NSViewController within the responder chain, allowing it to take care of the Touch Bar. There is also no need to worry about the App Delegate.

Related

Call function in another ViewController (macOS)

How can I communicate with another View Controller on Xcode Storyboards in any possible way?
Given the principle of encapsulation, the preferred way seems to be to call a function in the other ViewController.
(failed) ideas:
Using self.storyboard to instantiate a Controller with the specified Identifier, casting it to the correct View Controller subclass
instantiating the view controller with let c = specialViewController() [doesn't work because the instance's views haven't loaded]
connecting an IBOutlet to another NSViewController subclass [this one should work but doesn't]
Note: iOS solutions often are not the same as MacOS solutions
First failed idea code:
let spec_ref = self.storyboard!.instantiateController(withIdentifier: "specialSettings") as! SpecialSettings
spec_ref.save_spec_settings();
save_spec_function:
The spec_ref still cannot access IBOutlets in the other ViewController on the Storyboard, so it must not be the correct instance.

Reuse Storyboard ViewController - Parent / Child Viewcontroller

I want to make a ViewController base-class which I can reuse throughout the project.
I want to create a pop-up ViewController which I can adjust with multiple sub-classes which all share the same basic layout (inherited from the base-class). I would like the layout of the base class to be defined in a storyboard scene in an attempt to follow apple's guidelines (not using xib's). This also includes setting up all constraints in interface builder, and not in code.
All I want to do is the right thing :)
My problem is that if I start to subclass my ParentViewController (which has an associated scene in a Storyboard), the app won't let me show the ViewController. If I instantiate through the Storyboard ID, I can't cast it to my subclass. If I instantiate by creating an instance of the subclass-ViewController, it won't show, as the UI in the storyboard file is "locked" to the ParentViewController.
How do I make a base-ViewController with an associated scene in a storyboard file, which I can use various sub-classes (or the like).
To be concrete: I want to make a pop-up, which can vary slightly depending on the usage. I don't want to make init-methods for each variation, as that would defeat the purpose of attempting to split code.
Thanks for any help or comment!
object_setClass(Sets the class of an object.) will override instance of AViewController with BViewController Class. So on top of AViewController you can add some more methods.
when you have similar viewcontroller with small changes. you have to create different viewcontrollers. using this method you can create on basic viewcontroller with storyboard and reuse that viewcontroller .
class BViewController{
static func vcInstanceFromStoryboard() ->BViewController? {
let storyboard = UIStoryboard(name: "AViewController"), bundle: UIBundle.main)
let instance = storyboard.instantiateInitialViewController() as? AViewController
object_setClass(instance, BViewController.self) //
return (instance as? BViewController)!
}
.....
}
This is an example of how do we use it:
let vc = BViewController.vcInstanceFromStoryboard()
self.present(vc , animation : true)

What's the correct way to pass an object that will never change to an NSWindowController?

I have an NSWindowController that shows a table and uses another controller as the data source and delegate for an NSTableView. This second controller displays information from an object, which is passed in by the NSWindowController. That controller in turns has the object set as a property by the AppDelegate. It looks like this:
class SomeWindowController: NSWindowController {
var relevantThing: Thing!
var someTableController: SomeTableController!
#IBOutlet weak var someTable: NSTableView!
override func windowDidLoad() {
someTableController = SomeTableController(thing: relevantThing)
someTable.dataSource = someTableController
someTable.delegate = someTableController
}
}
In the AppDelegate I then do something like
func applicationDidFinishLaunching(_ aNotification: Notification) {
relevantThing = Thing()
someWindowController = SomeWindowController()
someWindowController.relevantThing = relevantThing
someWindowController.showWindow(nil)
}
Is this a reasonable approach? I feel like the implicitly unwrapped optionals used in SomeWindowController might be bad form. Also, relevantThing is not allowed to change in my case, so I feel a let would be more correct. Maybe the relevantThing should be made constant and passed in through the initializers? Or would that break the init?(coder: NSCoder) initializer?
I'd greatly appreciate any suggestions, as I'm trying to get a feel for the right way to do things in Swift.
A few things:
Is there any reason your are creating your window controller in code and not loading it from a storyboard/xib?
Generally, a better practice is to put all your 'controller' that relates to a view in a NSViewController and use NSWindowController only for stuff that relates to the window itself (e.g. toolbar, window management, etc).
Similarly to iOS, NSViewController is now integrated into the window/view lifecycle and responder chain. For many windows you don't even need to subclass NSWindowController.
XCode's app project template creates a storyboard with the window, main view and their controllers. This is a good starting point.
NSWindowController has a contentViewController property that is set to the NSViewController of the main content view (when loaded from storyboard). You generally don't need a separate view controller property for your view controller.
I think that usually, you want to minimize modifying your controllers from outside code and make them as independent as possible. This makes them more testable and reusable.
If your Thing instance is global for the entire application (as it appears from your code), you may want to consider adding it as a singleton instance to the Thing class and retrieving it from the NSViewController (e.g in viewDidLoad())
If you put your controllers/views in storyboard, you can connect the table's datasource/delegate there. And if this your main window, it can load and show it automatically when the app starts. But in any case, put your NSViewController/View wiring in the view controller.
If you want to separate logic between your main NSViewController into a more specialized view controller that handles a specific part of your view, you can use NSContainerView in Interface Builder to add additional view controllers to handle specific views.

Examples of Delegates in Swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been trying to learn how delegation with protocols work. I understood everything, but I can't think of when to use delegation other than when using table views and possibly scroll views.
In general, when is delegation used?
What is Delegation?
First of all, you should know that Delegation Pattern is not exclusive for iOS world:
In software engineering, the delegation pattern is a design pattern in
object-oriented programming that allows object composition to achieve
the same code reuse as inheritance.
But working with delegation in the iOS world is so common, I assume that you can see many of classes that provide a delegation/datasource for giving the ability to provide properties or behaviors for the used instance. It is one of main mechanisms of how objects talk to each other in CocoaTouch.
Alternatives:
However, delegation is not the only way to let objects talk to each other in iOS, you might want to know that there are:
NotificationCenter.
KVO (Key-Value Observing).
Completion handlers/Callbacks (using closures).
Target-Action.
Remark: in case if you are interested in comparing between them, you might want to check the following articles:
Communication Patterns.
When to Use Delegation, Notification, or Observation in iOS.
Delegates vs Observers.
When to use Delegation?
So, the question is: "So why should I use delegation instead of those options?"
I will try to make it simple; I would suggest the use of delegation when you have one to one relationship between two objects. Just to make it clearer, the goal of talking a little bit about the NotificationCenter is to try to make sense when delegations are used:
NotificationCenter represents one to many relationship; Simply, it works as: posting (notifying) a notification on a specific event and observing (get notified about) this notification -- it could be observed anywhere else; Logically, that's what one to many relationship means. It is a representation of the Observer Pattern.
How to Apply Delegation?
For the purpose of simplifying, I would mention it as steps:
Knowing the requirements: Each delegate has its own rules, listed in the delegate protocol which is a set of method signatures that you should implement for conforming this delegation.
Conforming for the delegation: it is simply letting your class to be a delegate, by marking it. For instance: class ViewController: UIViewController, UITableViewDelegate {}.
Connecting the delegate object: Marking your class to be a delegate is not enough, you need to make sure that the object you want to be confirmed by your class to give the required job to your class.
Implementing the requirements: Finally, your class have to implement all required methods listed in the delegate protocol.
For Example
Does it sounds a little confusing? What about a real-world example?
Consider the following scenario:
Imagine that you are building an application related to playing audios. Some of the viewControllers should have a view of an audio player. In the simplest case, we assume that it should have a play/pause button and another button for, let's say, showing a playlist somehow, regardless of how it may look like.
So far so good, the audio player view has its separated UIView class and .xib file; it should be added as a subview in any desired viewController.
Now, how can you add functionality to both of the buttons for each viewController? You might think: "Simply, I will add an IBAction in the view class and that's it", at first look, it might sound ok, but after re-thinking a little bit, you will realize that it will not be applicable if you are trying to handle the event of tapping the button at the controller layer; To make it clear, what if each viewController implemented different functionality when tapping the buttons in the audio player view? For example: tapping the playlist in "A" viewController will display a tableView, but tapping it in the "B" viewController will display a picker.
Well, let's apply Delegation to this issue:
The "#" comments represents the steps of "How to Apply Delegation?" section.
Audio Player View:
// # 1: here is the protocol for creating the delegation
protocol AudioPlayerDelegate: class {
func playPauseDidTap()
func playlistDidTap()
}
class AudioPlayerView: UIView {
//MARK:- IBOutlets
#IBOutlet weak private var btnPlayPause: UIButton!
#IBOutlet weak private var btnPlaylist: UIButton!
// MARK:- Delegate
weak var delegate: AudioPlayerDelegate?
// IBActions
#IBAction private func playPauseTapped(_ sender: AnyObject) {
delegate?.playPauseDidTap()
}
#IBAction private func playlistTapped(_ sender: AnyObject) {
delegate?.playlistDidTap()
}
}
View Controller:
class ViewController: UIViewController {
var audioPlayer: AudioPlayerView?
// MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
audioPlayer = AudioPlayerView()
// # 3: the "AudioPlayerView" instance delegate will implemented by my class "ViewController"
audioPlayer?.delegate = self
}
}
// # 2: "ViewController" will implement "AudioPlayerDelegate":
extension ViewController: AudioPlayerDelegate {
// # 4: "ViewController" implements "AudioPlayerDelegate" requirments:
func playPauseDidTap() {
print("play/pause tapped!!")
}
func playlistDidTap() {
// note that is should do a different behavior in each viewController...
print("list tapped!!")
}
}
Quick Tip:
As one of the most popular examples of using delegation is Passing Data Back between View Controllers.
Delegation is used when you want to pass some information or state of object A to another object B. Usually object B is the object that created object A.
I will list some situations where you would use delegation.
Yes you're right. table views and scroll views use delegates because they want to tell whoever is interested (usuall your view controller) that "someone selected a row!" or "someone scrolled the scroll view!". Not only do scroll views and table views use delegates, UITextField and UIDatePicker and a lot of other views use delegates too!
View Controllers also have delegates. For example, UIImagePickerController. The reason why is roughly the same as above - because the UIImagePickerController wants to tell you messages like "an image has been selected!". Another example would be UIPopoverControllerDelegate. This delegate tells you things like "the popover has been dismissed!"
Other classes that use delegates include CLLocationManager. This delegate tells you things like "the user's location has been detected" or "failed to detect the user's location".
You can use delegation in your code when a certain view controller of yours wants to send messages to other view controllers. If it is a settings view controller, it might send messages like "the font size setting has been changed!" and the view controller that cares about the font size setting changing will know and change the font size of a label or something.
Delegate Method to Selectionimages
Create baseClass And Insert the following code
Create Another class then insert code
Delegation in IOS world and mostly in MVC (Model View Controller)
is a way for the View to talk to the Controller and it's called "blind communication"
and delegation means to give the " leading stick " to another object ( doesn't really care who is taking over but usually the Controller) to control over components that the view can not control on it's own (remember it's only a view) or doesn't own
to make it more simple ....
the controller can talk to a view but the view can not talk to the controller without Delegation

Trouble subclassing SCNScene

I've been trying to subclass SCNScene as that seems like the best place to keep my scene related logic. Now I'm not sure wether that's reccomended so my first question is - Should I be subclassing SCNScene, and if not why not? The documentation seems to suggest it's common but I've read comments online that suggest I shouldn't subclass it. Scrap that, I was looking at the documentation for SKScene. The SCNScene class reference makes no mention of subclassing.
Assuming it's ok to structure my game that way, here's my progress
// GameScene.swift
import Foundation
import SceneKit
class GameScene: SCNScene {
lazy var enityManager: BREntityManager = {
return BREntityManager(scene: self)
}()
override init() {
print("GameScene init")
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func someMethod() {
// Here's where I plan to setup the GameplayKit stuff
// for the scene
print("someMethod called")
}
}
Note: I'm using lazy var as per the answer to this question
In my view controller, i'm trying to use GameScene like this
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a new scene
let scene = GameScene(named: "art.scnassets/game.scn")!
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// Should print "someMethod called"
scene.someMethod()
}
}
However, the call to GameScene.someMethod() triggers an EXEC_BAD_ACCESS error.
Also, if I omit the call to GameScene.someMethod, the scene loads correctly, but the overridden initializer in GameScene doesn't appear to be called.
I'm not sure what's going on here. It's clear there's something about subclassing in Swift that I've not understood. Or perhaps there' some aspect of order in which things are meant to run that I've missed.
Should I be subclassing SCNScene, and if not why not?
No, you don't need to subclass, and you're probably better off not subclassing. SCNScene is more like basic data/model classes (NSString, UIImage, etc) than like behavior/controller/view classes (UIViewController, UIControl, etc). That is, it's a general description of or container for something (in this case, a 3D scene) and doesn't really provide behavior. Since there's not much in the way of behavior, there's not much opportunity to override behavior with a subclass. (Nor is the class designed around subclass entry points meant to be overridden, like viewDidLoad and whatnot.)
While it's possible to subclass SCNScene, you don't gain much from doing so, and some APIs might not work as you expect...
However, the call to GameScene.someMethod() triggers an EXEC_BAD_ACCESS error.
Also, if I omit the call to GameScene.someMethod, the scene loads correctly, but the overridden initializer in GameScene doesn't appear to be called.
A .scn file is actually an NSKeyedArchiver archive, which means that the objects inside it have the same classes that were used to create it. when you call init(named:) on your SCNScene subclass, the superclass' implementation eventually calls through to NSKeyedUnarchiver unarchiveObjectWithData: to load the archive. Absent some unarchiver mangling, that method will instantiate a SCNScene, not an instance of your subclass.
Because you don't get an instance of your subclass, your subclass initializers aren't called, and attempting to call your subclass' methods results in a runtime error.
Aside: Why is SpriteKit different from SceneKit here? SKScene is a bit of an odd duck in that it's neither a pure model class nor a pure controller class. This is why you see a lot of projects, including the Xcode template, using an SKScene subclass. There are drawbacks to this approach, however — if you don't plan carefully, it gets too easy to wed your game logic tightly to your game data, which makes expanding your game (say, to multiple levels) require tedious coding instead of data editing. There's a WWDC 2014 session on this topic that's well worth watching.
So, what to do?
You have a few choices here...
Don't subclass. Keep your game logic in a separate class. This doesn't necessarily have to be a view controller class — you could have one or more Game objects that are owned by your view controller or app delegate. (This makes especially good sense if your game logic transitions between or manipulates the content of multiple scenes.)
Subclass, but arrange to put the stuff from an unarchived SCNScene into an instance of your subclass — instantiate your subclass, load an SCNScene, then move all children of its root node into your subclass' root node.
Subclass, but force NSKeyedUnarchiver to load your subclass instead of SCNScene. (You can do this with class name mappings.)
Of these, #1 is probably the best.
tl;dr: Extend SCNNode to generate your scene programmatically.
This started as a comment on Rickster's excellent answer but I could see it getting too long. I taught a course this quarter that spent a substantial amount of time on SceneKit. We subclassed SCNScene all the time and didn't run into any trouble.
However, after spending an hour just now reviewing the code I presented, the code the students wrote, and a ton of other sample code (from Apple and from other developers), I would not subclass SCNScene again.
None of the Apple sample code subclasses SCNScene. That should be a very strong clue. Handling the serialization (initWithCoder and the read from file) is a recurring question on StackOverflow. That's a second strong clue that you don't want to go there.
In all of the code I reviewed that subclassed SCNScene, the reason to do it was to generate the scene programmatically. That's Rickster's choice #2. But none of that code really needs to be on SCNScene. If you're building a bunch of nodes in particular configurations, adding lighting and look-at constraints, and setting up materials, it feels like you're building an SCNScene. But really you're building a tree of SCNNode instances.
So I think in hindsight, choice #2 does not provide a good enough reason to subclass. All of that construction can be done by writing a generator function, in an extension to SCNNode.
It's tempting to subclass SCNNode for this custom tree. Don't do it. You'll be able to save it and read it just fine (assuming you write the appropriate NSSecureCoding functions). But you will be unable to open your scene with the Xcode Scene Editor, because the Scene Editor doesn't know how to unarchive and instantiate your custom SCNNode subclasses.